83

I'm new to C# and learning new words. I find it difficult to understand what's the meaning of these two words when it comes to programming c#. I looked in the dictionary for the meaning and here's what I got:

Implicit

"Something that is implicit is expressed in an indirect way."

"If a quality or element is implicit in something, it is involved in it or is shown by it;"

Explicit

"Something that is explicit is expressed or shown clearly and openly, without any attempt to hide anything"

"If you are explicit about something, you speak about it very openly and clearly."

I would like to understand it in C#.

Thanks for your help.

Cheers


additional info:

Here is a part of sentence in the book what I'm reading now which has this word "implicit"

"This means that Area and Occupants inside AreaPerPerson( ) implicitly refer to the copies of those variables found in the object that invokes AreaPerPerson( )"

I quite don't understand what this sentence here trying to say.

3
  • maybe I just never run into them. But in what context are you talking about? I've never heard about explicit and implicit applied in C# before. Jul 24, 2009 at 9:43
  • Indeed, give the range of answers there are many contexts in C#. Jul 24, 2009 at 9:45
  • The use of "implicit" in the text you quote is just as mysterious to you as it is to me. It probably makes sense in that context, but it certainly isn't a term from general C# programming parlance. Jul 24, 2009 at 10:03

9 Answers 9

150

The implicit and explicit keywords in C# are used when declaring conversion operators. Let's say that you have the following class:

public class Role
{
    public string Name { get; set; }
}

If you want to create a new Role and assign a Name to it, you will typically do it like this:

Role role = new Role();
role.Name = "RoleName";

Since it has only one property, it would perhaps be convenient if we could instead do it like this:

Role role = "RoleName";

This means that we want to implicitly convert a string to a Role (since there is no specific cast involved in the code). To achieve this, we add an implicit conversion operator:

public static implicit operator Role(string roleName)
{
    return new Role() { Name = roleName };
}

Another option is to implement an explicit conversion operator:

public static explicit operator Role(string roleName)
{
    return new Role() { Name = roleName };
}

In this case, we cannot implicitly convert a string to a Role, but we need to cast it in our code:

Role r = (Role)"RoleName";
3
  • 10
    @tintincute: Very rarely! Custom conversions are only very occasionally useful, just like user-defined operators.
    – Jon Skeet
    Jul 24, 2009 at 9:56
  • Jon is right. I don't think I have ever used this in production code. Jul 24, 2009 at 10:36
  • 2
    thanks a lot! i'm having some difficulty to understand the technical terms sometimes. this is very well explained. thanks again Jul 24, 2009 at 12:11
73

In general

  • Implicit: something is being done for you automatically.
  • Explicit: you've written something in the source code to indicate what you want to happen.

For example:

int x = 10;
long y = x; // Implicit conversion from int to long
int z = (int) y; // Explicit conversion from long to int

Implicit and explicit are used quite a lot in different contexts, but the general meaning will always be along those lines.

Note that occasionally the two can come together. For instance:

int x = 10;
long y = (long) x; // Explicit use of implicit conversion!

(An explicit conversion is one which has to be stated explicitly; an implicit version is one which can be used implicitly, i.e. without the code having to state it.)

7
  • Wouldn't var's als be a nice context of implicit and explicit typing here? implicit var impl = new { Field1 = "EUR", Field2 = 9.40 }; and explicit with class definition public class Conversion { string Field1 { get; set; } public double Field2 { get; set; } } and assign Conversion expl = new Conversion(); expl.Field1 = "EUR"; expl.Field2 = 9.40; Dec 15, 2011 at 7:52
  • @Jonas: I'm not really sure what you're getting at here, I'm afraid.
    – Jon Skeet
    Dec 15, 2011 at 7:55
  • Okey, I give it a new try. var is considered as "implicitly typed variables" in C#? Dec 15, 2011 at 8:03
  • 1
    @Jonas: Yes. Your previous comment also included an anonymous type, but that's slightly separate from implicit typing. Note that there are also object initializers, so you could use var conversion = new Conversion { Field1 = "EUR", Field = 9.40 };
    – Jon Skeet
    Dec 15, 2011 at 8:04
  • @Skeet Thank's, your probably right, where the anonymous type are implicitly declared? Another context of "implicit/explicit" term. Your sample would, to me, correspond to var st = new StreamReader(), where there are a smarter object in behind? But, even there, wouldn't we, for readibility, use Stream st = new Stream() :). Dec 15, 2011 at 8:15
11

Consider you have two classes:

internal class Explicit
{
    public static explicit operator int (Explicit a)
    {
        return 5;
    }
}


internal class Implicit
{
    public static implicit operator int(Implicit a)
    {
        return 5;
    }
}

and two objects:

var obj1 = new Explicit();
var obj2 = new Implicit();

you can now write:

int integer = obj2; // implicit conversion - you don't have to use (int)

or:

int integer = (int)obj1; // explicit conversion

but:

int integer = obj1; // WON'T WORK - explicit cast required

Implicit conversion is meant to be used when conversion doesn't loose any precision. Explicit conversion means, that you can loose some precision and must state clearly that you know what you're doing.

There is also a second context in which implicit/explicit terms are applied - interface implementation. There are no keywords in that case.

internal interface ITest
{
    void Foo();
}

class Implicit : ITest
{
    public void Foo()
    {
        throw new NotImplementedException();
    }
}

class Explicit : ITest
{
    void ITest.Foo() // note there's no public keyword!
    {
        throw new NotImplementedException();
    }
}

Implicit imp = new Implicit();
imp.Foo();
Explicit exp = new Explicit();
// exp.Foo(); // won't work - Foo is not visible
ITest interf = exp;
interf.Foo(); // will work

So when you use explicit interface implementation, interface's methods are not visible when you use concrete type. This can be used when interface is a helper interface, not part of class'es primary responsibility and you don't want additional methods to mislead someone using your code.

2

I think this link makes it pretty clear what an implicit conversion is - it's one where you don't need to explicitly cast the value in an assignment. So, instead of doing

myDigit = (Digit) myDouble 

...you can just do:

myDigit = myDouble;
1

Being explicit in C# is mainly about showing your intentions clearly and unambiguously.

For example:

class MyClass
{
    string myField;

    void MyMethod(int someNumber)
    {

    }
}

In the above code the visibility of the class, field and method are all implied. They use the compiler defaults.

Now, I can never remember what the compiler defaults are, and maybe your colleagues can't either, so rather than rely on everyone remembering what the defaults are, you can be explicit.

public class MyClass
{
    private string myField;

    public void MyMethod(int someNumber)
    {
    }
}
0

Implicit can be taken as implied, but explicit means that you state it must be done yourself. Like with casts. Here is an implicit cast:

int implicit;
implicit = 7.5;

The value '7.5' will implicitly be cast as an int. This means the compiler does it for you.

Here is explicit:

int explicit;
explicit = (int)7.5;

Here you tell the compiler that you want it cast. You explicitly declare the conversion. Hope that helps. Source: http://cboard.cprogramming.com/cplusplus-programming/24371-implicit-explicit.html

0

Because C# is statically-typed at compile time.

Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

Explicit conversions (casts): Explicit conversions require a cast expression. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static explicit operator Person(Employe employe) => new Person { Id = employe.Id, Name = employe.Name };
}

public class Employe
{

    public int Id { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }

    public static implicit operator Employe(Person person) => new Employe { Id = person.Id, Name = person.Name };
}

static void Main(string[] args)
{
    Person person = new Person() { Id = 1, Name = "Reza" };

    //implicit operator
    Employe employe = person;
    employe.Family = "Jenabi";

    //explicit operator
    Person person1 = (Person)employe;
}
0

Microsoft code generators use keyword "var" for implicit, but I think it's important to note that

var builder = WebApplication.CreateBuilder(args);

and

WebApplicationBuilder? builder = WebApplication.CreateBuilder(args); 

are the same but

var builder = WebApplication.CreateBuilder(args);

and

WebApplicationBuilder builder = WebApplication.CreateBuilder(args); 

are NOT the same.

For code clarity I prefer Explicit always, but as you can see Microsoft's code generators do not. From a code execution standpoint, there is NO performance difference.

0

Let's understand this with an example of converting Lead to Opportunity. If we define the Lead as

public class Lead
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and we want to convert it into Opportunity as

public class Opportunity
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Worth {get;set;} 
}   

Map & Convert

In order to do that we need to create a new Instance of Opportunity and then copy the values, so we created a new function to do that and this needs to be in a in a class.

public Opportunity Convert(Lead lead)
{
    Opportunity opp = new Opportunity();
    opp.Id = lead.Id.ToString();
    opp.FirstName = lead.FirstName;
    opp.LastName = lead.LastName;
    return opp;
}

So we move that method inside the Opportunity class as and make itstatic so that it can be called as Opportunity.Convert():

public class Opportunity
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Worth {get;set;} 
    
    public static Opportunity Convert(Lead lead)
    {
        Opportunity opp = new Opportunity();
        opp.Id = lead.Id.ToString();
        opp.FirstName = lead.FirstName;
        opp.LastName = lead.LastName;
        return opp;
    }
}

//main
void Main()
{
    Lead lead = new Lead();
    lead.Id = Guid.NewGuid();
    lead.FirstName = "Vinod";
    lead.LastName = "Srivastv";
    lead.Dump();
    

    Opportunity opp = Opportunity.Convert(lead);
    opp.Dump();
}

But with explicit and implicit we can declare conversion operators so that we don't have to call the Convert method of the Opportunity class.

implicit Example

In the implicit conversion we don't need to cast the object manually as it is done implicitly.

public class Opportunity
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Worth {get;set;} 
    
    public static implicit operator Opportunity(Lead lead)
    {
        Opportunity opp = new Opportunity();
        opp.Id = lead.Id.ToString();
        opp.FirstName = lead.FirstName;
        opp.LastName = lead.LastName;
        return opp;
    }
}

//main
void Main()
{
    Lead lead = new Lead();
    lead.Id = Guid.NewGuid();
    lead.FirstName = "Vinod";
    lead.LastName = "Srivastv";
    lead.Dump();
    
    // here the lead is implicitly converted to opportunity 
    //and we get rid of the Convert Method from above 
    Opportunity opp = lead;
    opp.Dump();
}

enter image description here

explicit Example

Now we just made the change of the keyword from implicit to explicit from the code above:

public class Opportunity
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Worth {get;set;} 
    
    public static explicit operator Opportunity(Lead lead)
    {
        Opportunity opp = new Opportunity();
        opp.Id = lead.Id.ToString();
        opp.FirstName = lead.FirstName;
        opp.LastName = lead.LastName;
        return opp;
    }
}

//main
void Main()
{
    Lead lead = new Lead();
    lead.Id = Guid.NewGuid();
    lead.FirstName = "Vinod";
    lead.LastName = "Srivastv";
    lead.Dump();
    
    //CS0266 Cannot implicitly convert type '.Lead' to 'Opportunity'. 
    //An explicit conversion exists (are you missing a cast?)
    //Opportunity opp = lead;
    
    //This is an example of explicit conversion, see the casting
    Opportunity opp = (Opportunity)lead;
    opp.Dump();
}

As we change the keyword the compiler will throw error as An explicit conversion exists (are you missing a cast?) so we need to cast the Lead object to opportunity with (Opportunity) as above.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.