Yar
Yar

Reputation: 7457

Passing an inconstant default parameter to a C# method

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;
}

Upvotes: 3

Views: 82

Answers (2)

Alexander
Alexander

Reputation: 4173

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;
  }
}

Upvotes: 1

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

You could use an overloaded method:

public static HttpResponseMessage GenerateToken()
{
    return GenerateToken(defUserInfo);
}
public static HttpResponseMessage GenerateToken<T>(T userInfo)
{
   // stuff
    return response;
}

Upvotes: 10

Related Questions