Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best practice in C# for type casting? [duplicate]

Tags:

c#

.net

Which method is best practice to type casting and checking ?

Employee e = o as Employee;
if(e != null)
{
 //DO stuff
}

OR

if(o is Employee)
{
Employee e = (Employee) o;
 //DO stuff
}
like image 921
vrnithinkumar Avatar asked Sep 25 '15 06:09

vrnithinkumar


People also ask

What does best practice mean in programming?

Coding best practices or programming best practices are a set of informal rules (best practices) that software developers in computer programming follow to improve software quality.


1 Answers

At least there are two possibilities for casting, one for type checking and a combination of both called pattern matching. Each has its own purpose and it depends on the situation:

Hard cast

var myObject = (MyType)source;

You normally do that if you are absolutely sure if the given object is of that type. A situation where you use it, if you subscribed to an event handler and you cast the sender object to the correct type to work on that.

private void OnButtonClick(object sender, EventArgs e)
{
    var button = (Button)sender;

    button.Text = "Disabled";
    button.Enabled = false;
}

Soft cast

var myObject = source as MyType;

if (myObject != null)
    // Do Something

This will normally be used if you can't know if you really got this kind of type. So simply try to cast it and if it is not possible, simply give a null back. A common example would be if you have to do something only if some interface is fullfilled:

var disposable = source as IDisposable;

if(disposable != null)
    disposable.Dispose();

Also the as operator can't be used on a struct. This is simply because the operator wants to return a null in case the cast fails and a struct can never be null.

Type check

var isMyType = source is MyType;

This is rarely correctly used. This type check is only useful if you only need to know if something is of a specific type, but you don't have to use that object.

if(source is MyType)
   DoSomething();
else
   DoSomethingElse();

Pattern matching

if (source is MyType myType)
    DoSomething(myType);

Pattern matching is the latest feature within the dotnet framework that is relevant to casts. But you can also handle more complicated cases by using the switch statement and the when clause:

switch (source)
{
    case SpecialType s when s.SpecialValue > 5
        DoSomething(s);
    case AnotherType a when a.Foo == "Hello"
        SomethingElse(a);
}
like image 194
Oliver Avatar answered Sep 20 '22 10:09

Oliver