Take this example:
interface IEntity {
string Name { get; set; }
}
class Product : IEntity {
public string Name { get; set; }
public int Count { get; set; } // added member
}
class Client {
void Process() {
var product = new Product();
int count = product.Count; // this is valid
}
}
In the example above, what is the type of product? Is it IEntity or Product? It appears that product is of type concrete implementation (Product). If that is the case, shouldn't var be used only in special circumstances. But I see that tools like resharper recommend using var by default. Shouldn't one program to an interface?
var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.
var data type was introduced in C# 3.0. var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration.
By using “var”, you are giving full control of how a variable will be defined to someone else. You are depending on the C# compiler to determine the datatype of your local variable – not you. You are depending on the code inside the compiler – someone else's code outside of your code to determine your data type.
As you probably already know, C# has supported the variable type var since version 3.0.
You are not actually "programming to interfaces" if you are still instantiating the concrete class within the method, as the dependency to the concrete Product class still remains. In order to properly program-to-interfaces you must remove the new instantiation, for example by using a factory or IoC.
What if you had a Product like ...
class Product : IFirst, ISecond, IThrid
The only rational thing the complier can do is what it does. I don't limit my use of var
, I use it everywhere. I think it makes code far more readable. In this case, I agree with ReSharper across the board.
If you want Product
to be of type IEntity
, try this:
var product = new Product() as IEntity;
That said, yes you should program to an interface, but in your case you're instantiating the concrete type directly. If you've already created a dependency to the concrete type, just use the concrete type. If not, use a factory or injection to get an instance of the interface. var
will work with those rather well. For example:
public class MyExtremelySimpleFactoryExampleClass
{
public IEntity Instantiate()
{
return new Product();
}
}
// elsewhere in your code...
var item = myFactory.Instantiate(); // item is of type IEntity
Finally, no, I don't think var
should be used only in "special circumstances". I find it quite useful and use it almost always.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With