2

Given a method:

private static T GetBin<T>(string file)

Is it possible to set T to default to object, if I use:

public static byte[] ToJSONBytes<T>(this T obj) 

It defaults to whatever obj is set as. However, this GetBin method Deserializes a file, using the BinaryFormatter, and as you all know, it returns an object. My method explicitly casts it to T and then returns it, but I want to make T optional and default to object.

1
  • 1
    Then why not just return object and let the caller cast it if they want to? Commented Mar 12, 2013 at 16:48

1 Answer 1

3

Generic type parameters cannot have default values.

However, they can have overloads:

private static object GetBin(string file) { return GetBin<object>(file); }
Sign up to request clarification or add additional context in comments.

3 Comments

But generic arguments aren't part of the signature, so that won't compile due to ambiguity errors, no?
@Servy: Compiles fine in LINQPad, just tested it.
@Servy: Generic overloading ((like this) does work. You're thinking of overload resolution with constraints; blogs.msdn.com/b/ericlippert/archive/2009/12/10/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.