jlee
jlee

Reputation: 3175

Generic contraints

I've got a class that I want to enforce some generic constraints on when created

Myobject.cs

    public class MyObject<T> where T : ObjectBase, new()
    {
        public MyObject()
        {
        }

        public bool Validate(out ServiceError? message)
        {
            // validation
        }
    }

ObjectBase.cs

public abstract class ObjectBase
{
    public abstract bool Validate(out ServiceError? message);
}

I'm wondering if there is any way to avoid having to place generic constraints for T every time I have a function such as this:

ObjectRepo.cs

public void Put<T>(MyObject<T> obj)
  where T : ObjectBase, new()
{
    // code
}

If the constraints for T are specified in the MyObject class, is there a reason I have to re-specify every single time I use MyObject as a parameter?

Upvotes: 2

Views: 75

Answers (1)

George Vovos
George Vovos

Reputation: 7618

Don't redefine T on your method if you have it on the class

public class MyObject<T> where T : ObjectBase, new()
{
    //public void Put<T>(MyObject<T> obj)//doesn't work
    public void Put(MyObject<T> obj)//works
    {
        // code
    }
}

Update
If Put is in another class your best solution it to refactor your code and move all the T related method in the same class (and add the constrain on the class)

Update 2
If update 1 is not possible ,it might worth checking if you can replace your T with ObjectBase or another base class

Upvotes: 6

Related Questions