James_RedEagle
James_RedEagle

Reputation:

var keyword with Activator.CreateInstance?

There's been some question where I work about use of the var keyword when casting the result of Activator.CreateInstance to an interface type. As I understand var, the following snippet pairs are pretty much identical between the var version and the explicit type version:

// Direct cast
var thing = (IThing)Activator.CreateInstance(Type.GetType(thingType));
IThing thing = (IThing)Activator.CreateInstance(Type.GetType(thingType));

// Casting with as
var thing = Activator.CreateInstance(Type.GetType(thingType)) as IThing;
IThing thing = Activator.CreateInstance(Type.GetType(thingType)) as IThing;

Are there any subtle differences I'm missing that might change Intellisense or runtime behavior?

Upvotes: 1

Views: 265

Answers (4)

bruno conde
bruno conde

Reputation: 48265

No there is no difference. Also I don't see any problem in using the var keyword.

In terms of readability, looking at the following lines of code you easily see witch Type the var is:

var thing = (IThing)Activator.CreateInstance(Type.GetType(thingType));
var thing = Activator.CreateInstance(Type.GetType(thingType)) as IThing;

Upvotes: 1

ChrisF
ChrisF

Reputation: 137148

In each case declaring thing as var or IThing is synonymous.

There are differences between the cast and using as - the latter will return null if the item isn't what you're trying to convert to.

Upvotes: 1

Dan Herbert
Dan Herbert

Reputation: 103407

There is no difference. The 'var' keyword doesn't do anything magical, it uses compile time type inference, similar to how generics work.

Once it's compiled, there is no difference. You can prove this with your IDE by hovering over the variable name where it is being used (other than where it is declared). A tooltip should pop up showing you the type. Both variables should have the same type when hovered over.

Upvotes: 2

Jake Pearson
Jake Pearson

Reputation: 27717

var and IThing are identical. You just save 3 keystrokes.

Upvotes: 0

Related Questions