Ignoring Types

Strongly typed vs dynamically typed

Strongly typed means that the compiler will complain if a method does not exist in the class specified during variable declaration. C# is strongly typed, but if you are used to dynamically typed languages (like Python), you can do that too.

//strongly typed
Animal duck = Factory.MakeDuck();
duck.quack();   //compile error because quack() is not defined in Animal even though you know the underlying object is a duck

Dynamically typed means that the compiler will not care whether the method exists or not (it will be done at runtime)

//dynamically typed
dynamic duck = Factory.MakeDuck();
duck.quack();   //a method called "quack()" will be checked at runtime.  Also, the autocomplete will not work for dynamic variables.

There may be cases where you will need to ignore the object type in order to make classes decoupled. It’s highly recommended that you have unit tests that will catch type errors.

I typically use dynamic when parsing JSON data with arbitrary/unknown fields.

Tip: Type checking and casting in one line

Here’s how you check whether an object is of a certain type

if(someObject is Duck d)    //shorthand for typecasting someObject to "Duck" within the if block
{
    d.quack();  
}

get yourself on the email list

//Powered by MailChimp - low volume, no spam

comments powered by Disqus