Is it possible to create generic classs without type argument?

Viewed 94

To my knowledge this is not possible, but I rather ask and make a fool of myself :P.

So, I have generic class Operation<T> where T is the return value of said operation. This class also tells me if an operation was successful, if not there are messages (ex. the exception message, etc.)

public class Operation<T>
{

    public T Value { get; set; }
    public bool Succeeded { get; set; }
    public string[] Messages { get; set; }

    internal Operation(T value)
    {
        Value = value;
        Succeeded = true;
    }

    internal Operation(bool succeeded, string[] messages = null)
    {
        Succeeded = succeeded;
        Messages = messages;
    }


    public static Operation<T> Completed(T value)
    {
        return new Operation<T>(value);
    }

    public static Operation<T> Success()
    {
        return new Operation<T>(true);
    }

    public static Operation<T> Failure(string[] messages)
    {
        return new Operation<T>(false, messages);
    }
}

In some cases, I only want to say that the operation was successful or not, and I don't need the T value.

Example pseudo code:

    // Example operation where I need T value
    Operation<int> op = _SumTwoIntegersService.Sum(1, 2); 
    Console.WriteLine(operation.Value); // 3

    // Example operation where I only need the operation status
    Operation op = _UserService.Add(user); // Is this possible? Initiate Operation without the type argument
    if (op.Succeeded)
        return Ok();
    else
        return BadRequest(op.Messages);
1 Answers

In some cases, I only want to say that the operation was successful or not, and I don't need the T value.

In that case, I'd basically follow the model of Task and Task<T>: have a non-generic base class with everything that doesn't depend on T, and a generic derived class for everything T-specific:

public class Operation
{
    public bool Succeeded { get; set; }
    public string[] Messages { get; set; }

    // Constructors, other methods
}

public class Operation<T> : Operation
{
    public T Value { get; set; }

    // Constructors, other methods
}
Related