3

I want to pass an object as the default value for defUserInfo method, but It's not possible since it's not a compile-time constant. Is there any other way to make this work?

private static CustomerIdentifications defUserInfo = new CustomerIdentifications { CustomerID = "1010", UniqueIdentifier = "1234" }; public static HttpResponseMessage GenerateToken<T>(T userInfo = defUserInfo) { // stuff return response; } 

2 Answers 2

10

You could use an overloaded method:

public static HttpResponseMessage GenerateToken() { return GenerateToken(defUserInfo); } public static HttpResponseMessage GenerateToken<T>(T userInfo) { // stuff return response; } 
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is a more robust approach than using magic values
1

If CustomerIdentifications were a struct, you could kind of simulate default values, by using struct properties instead of fields:

using System; struct CustomerIdentifications { private string _customerID; private string _uniqueIdentifier; public CustomerIdentifications(string customerId, string uniqueId) { _customerID = customerId; _uniqueIdentifier = uniqueId; } public string CustomerID { get { return _customerID ?? "1010"; } } public string UniqueIdentifier { get { return _uniqueIdentifier ?? "1234"; } } } class App { public static void Main() { var id = GenerateToken<CustomerIdentifications>(); Console.WriteLine(id.CustomerID); Console.WriteLine(id.UniqueIdentifier); } public static T GenerateToken<T>(T userInfo = default(T)) { // stuff return userInfo; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.