Reputation: 102
This may be a stupid question but I which I could really get some insight in this thing. I'm trying to make some projects and to do this effeciently I try to study every day to learn new things.
I often take examples on github to study from but I've seen this pointless things which I really don't understand. I have seen a function like this
public void SomeNewFunction(object value, Type type)
{
VerifyValueAndType(value, type);
//do something
}
private void VerifyValueAndType(object value, Type type)
{
if (type == null)
{
if (value != null)
{
throw new ArgumentNullException(nameof(type));
}
}
else if (value != null)
{
if (!type.IsAssignableFrom(value.GetType()))
{
//throw another error
}
}
}
Now what I don't understand is why they ask you to give the object type separately and not use the "value.getType()"? especially when they eventually use the "value.getType()" anyway to compare the types?
I been thinking it could be because of performence but then again, if they just use the getType() immediatly then they wouldn't have to verify.
Can someone explain the use of this?
Upvotes: 0
Views: 46
Reputation: 5156
It really depends on the purpose, but, say you are building a dependency container, for example. you want to register some implementation to an interface, so you can do
Register(myServiceImplementation, typeof(IMyService));
This allows you to be very explicit about what is being registered. Using GetType
would yield the type of the implementation, and even if you used reflection to get the whole type/interface tree, it would be less specific.
That said, a better pattern for this kind of thing would be
void Register<TInterface>(TInterface implementation);
This could be called like so:
Register<IMyService>(myServiceImplementation);
And would be a bit more type-safe, the validation could be skipped entirely since the error would already have occurred at compile-time.
Upvotes: 2