Casting an object to the same type & the effect on performance
c#, casting, performance
Solution
The cast you've shown is a "natural" reference type cast. It doesn't change anything about the object - it just ensures that the object is of an appropriate type (either the one you're casting to or a subclass). If the object is of the wrong type, an exception is thrown. No extra objects are created, or anything like that.
It's not free of course - but it would be rare for this to be a performance bottleneck.
It's not clear why you've got this code though:
if (objToReturn != null)
{
return objToReturn;
}
return null;
Why not just use:
return objToReturn;
? That will behave exactly the same way. Then your entire method can be reduced to just:
public T Get<T>(string key) where T : class
{
return (T) _cache[key];
}
EDIT: Note that you should not just use `as` instead, unless you really want values of the wrong type to silently be returned as `null`. For example:
cache[key] = new object();
string x = cache[key] as string; // x is null
string y = (string) cache[key]; // Exception
Problem
A question regarding the performance of casting an object to the same type (I know that sounds odd at first but let me put it in context) ``` public T Get<T>(string key) where T : class { var objToReturn = (T)_cache[key]; if (objToReturn != null) { return objToReturn; } return null; } ``` The above is a snippet of code for attempting to get an object of type `T` out of a `CacheObject` where the type is strongly typed by the caller. Know seeing as the type of the object is strongly typed, I am wondering about the line: ``` var objToReturn = (T)_chache[key]; ``` Will this actually invoke a cast and convert instance in the cache to another instance and return that or will the types be found to be the same to the cast simply ignored. I ask as the ability to cast will be useful in later development to the application that this cache is being used in for getting derived types but I don't want to breed in a potentially major performance hit early on. Thoughts and thank you.