I want to write a method that accepts a single IBar and call its Baz method.
This throws when obj is null:
void Foo<T>(T obj)
where T : IBar
=> obj.Baz();
This boxes obj when it is a value type:
void Foo<T>(T obj)
where T : IBar
=> obj?.Baz();
This doesn't call Baz if obj is zero:
void Foo<T>(T obj)
where T : IBar
{
if (!EqualityComparer<T>.Default.Equals(obj, default(T)))
obj.Baz();
}
And here, Foo(new Bar()) always picks the generic method no matter if Bar is a class or struct:
void Foo<T>(T obj)
where T : struct, IBar
=> obj.Baz();
void Foo(IBar obj)
=> obj?.Baz();
This makes my eyes bleed:
void FooVal<T>(T obj)
where T : struct, IBar
=> obj.Baz();
void FooRef(IBar obj)
=> obj?.Baz();
So is there a best practice for this? I'm open to all suggestions.
Edit:
The question is marked as duplicate with Generic constraints, where T : struct and where T : class and with the old title, it was. So I've updated the title to convey my problem better. What I'm asking is that how can I call a generic method and use the argument only if it is not null, without boxing.
Some workarounds explained for the linked question may be used to answer this one but I still believe this is a fundamentally different question.