explicit and implicit c#

51,088

Solution 1

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";

Solution 2

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.)

Solution 3

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.

Solution 4

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;

Solution 5

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)
    {
    }
}
Share:
51,088

Related videos on Youtube

tintincutes
Author by

tintincutes

NewBie in a programming world New to Java World :-) Just started googletalk:athens143

Updated on July 05, 2022

Comments

  • tintincutes
    tintincutes almost 2 years

    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.

    • Jimmy Chandra
      Jimmy Chandra almost 15 years
      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.
    • Colin Mackay
      Colin Mackay almost 15 years
      Indeed, give the range of answers there are many contexts in C#.
    • reinierpost
      reinierpost almost 15 years
      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.
  • Jon Skeet
    Jon Skeet almost 15 years
    @tintincute: Very rarely! Custom conversions are only very occasionally useful, just like user-defined operators.
  • Fredrik Mörk
    Fredrik Mörk almost 15 years
    Jon is right. I don't think I have ever used this in production code.
  • tintincutes
    tintincutes almost 15 years
    thanks a lot! i'm having some difficulty to understand the technical terms sometimes. this is very well explained. thanks again
  • Independent
    Independent over 12 years
    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;
  • Jon Skeet
    Jon Skeet over 12 years
    @Jonas: I'm not really sure what you're getting at here, I'm afraid.
  • Independent
    Independent over 12 years
    Okey, I give it a new try. var is considered as "implicitly typed variables" in C#?
  • Jon Skeet
    Jon Skeet over 12 years
    @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 };
  • Independent
    Independent over 12 years
    @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() :).
  • Jon Skeet
    Jon Skeet over 12 years
    @Jonas: Your StreamReader and Stream example isn't clear to me, as the two aren't the same thing at all... sorry, I'm still just not sure what you're trying to ask.
  • Independent
    Independent over 12 years
    @Skeet Sorry for the typo. The comment was of course supposed to take 1 object as a sample. We can end up here, the question was how the use of anonymous typing and strong typing refer to implicit/explicit.