Rohit
Rohit

Reputation: 300

Need Generic Constructor in C#

I want to make generic constructor for the following code.

As the different enum will be added in following scenario . I want that class to be generic.

using System.Runtime.Serialization;
using TT.SharedServices.Utils;

namespace TT.Core
{
[DataContract(Namespace = "SharedServices")]
public class Error
{
    /// <summary>
    /// Gets or Sets Error Code
    /// </summary>
    [DataMember]
    public int ErrorCode { get; set; }

    /// <summary>
    /// Gets or Sets detailed error message
    /// </summary>
    [DataMember]
    public string ErrorMessage { get; set; }


    public Error()
    {
        ErrorMessage = NullValues.NullString;
        ErrorCode = NullValues.NullInt;
    }

    public Error(AuthenticateErrorType errorType, string errorMessage)
    {
        ErrorCode = (int) errorType;
        ErrorMessage = errorMessage;
    }

    public Error(LoadMemberErrorType errorType, string errorMessage)
    {
        ErrorCode = (int)errorType;
        ErrorMessage = errorMessage;
    }
 }
}

Suggest me best optimized way to overcome this scenario?

Upvotes: 2

Views: 111

Answers (3)

Nitin Joshi
Nitin Joshi

Reputation: 1668

User following code:

[DataContract(Namespace = "SharedServices")]
public class Error<T>
{
    /// <summary>
    /// Gets or Sets Error Code
    /// </summary>
    [DataMember]
    public int ErrorCode { get; set; }

    /// <summary>
    /// Gets or Sets detailed error message
    /// </summary>
    [DataMember]
    public string ErrorMessage { get; set; }


    public Error()
    {
        ErrorMessage = NullValues.NullString;
        ErrorCode = NullValues.NullInt;
    }

    public Error(T errorType, string errorMessage)
    {
        ErrorCode = Convert.ToInt32(errorType);
        ErrorMessage = errorMessage;
    }

}

Upvotes: 0

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

You can think of creating a generic factory method to create instanced instead of constructor:

public static Error CreateError<T>(T errorType, string errorMessage)
{
    // Add if (!typeof(T).IsEnum) throw ... here if you wish
    return new Error()
    {
        ErrorCode = (int)(object)errorType,
        ErrorMessage = errorMessage
    };
}

Hopefully, in future version of C# it will be easier, as mentioned in point 8. Constructor type parameter inference in article Probable C# 6.0 features illustrated.

Upvotes: 1

Ales Ruzicka
Ales Ruzicka

Reputation: 2800

You can use non-generic code such as

public Error(Enum errorType, string errorMessage)
{
    ErrorCode = (int)(object)errorType;
    ErrorMessage = errorMessage;
}

Generis would not help that much anyway

Upvotes: 3

Related Questions