0

Given the following code:

    public static TUnbox UnboxAndNullCheck<TUnbox, TBox>(TBox obj, string msg = "Unboxing error") where TUnbox : class, TBox
    {
        var unboxObj = obj as TUnbox;
        if (unboxObj == null)
            throw new ArgumentNullException( msg );
        return unboxObj;
    }

It seems calling it requires both type parameters as so:

UnboxAndNullCheck<SubClass, BaseClass>( obj );  

Is it possible to call it in a way where you do not have to specify the type of obj?

UnboxAndNullCheck<SubClass>( obj );  
cubesnyc
  • 1,385
  • 2
  • 15
  • 32
  • I dont think so its possible just like we cant have `Dictionary` – Vivek Nuna Jun 10 '20 at 06:44
  • What does this give your calling code that just using `as` does not? – Caius Jard Jun 10 '20 at 06:49
  • 2
    Also, it uses ArgumentNullException incorrectly; ANE is for when an argument is null, not for when something in code is null (that's what NullReferenceException is for), resulting in a null. This would be confusing to fellow developers - "why am I getting Arg Null when I'm certainly providing something that has a value?" – Caius Jard Jun 10 '20 at 06:51
  • I gave an example to illustrate the question I was asking. – cubesnyc Jun 10 '20 at 08:18

1 Answers1

0

Fix the type?

public static TUnbox UnboxAndNullCheck<TUnbox> (object obj, string msg = "Unboxing error") where TUnbox : class

But I'm really not sure what this gives you over just using is and as.. other than confusingly throwing an error in runtime saying an argument passed didn't have a value when it clearly did, and I'm really not sure what it gives you over just doing a cast. If TBox can be cast to TUnbox, it works. If it doesn't, it throws an exception

//this
var x = UnboxAndNullCheck<TUnbox>(myTBox);

//is just the same as this, except this is more compact  and throws the right exception
var x = (TUnbox)myTBox;
Caius Jard
  • 72,509
  • 5
  • 49
  • 80