explicit and implicit c#

C#DictionaryImplicitExplicit

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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 - C#

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)
    {
    }
}

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontintincutesView Question on Stackoverflow
Solution 1 - C#Fredrik MörkView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#maciejkowView Answer on Stackoverflow
Solution 4 - C#Gary McGillView Answer on Stackoverflow
Solution 5 - C#Colin MackayView Answer on Stackoverflow
Solution 6 - C#Roque MejosView Answer on Stackoverflow
Solution 7 - C#Reza JenabiView Answer on Stackoverflow
Solution 8 - C#RobView Answer on Stackoverflow