Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Constraints in C# Extension Methods

Tags:

c#

.net

generics

I would like to provide a extension method but have some sort of prevention in what can call it.

This is what I have:

using System;

public class Test
{
    public static void Main()
    {
        Person p = new Person();
            p.IsValid();
    }
}

public class Person
{
    public string Name {get;set;}
}

public static class ValidationExtensions
{
    public static void IsValid<T>(this T parent) where T : class
    {
        throw new NotImplementedException("test");
    }
}

However, this doesnt stop someone doing "this is a dumb idea".IsValid();

I could mark the Person object with an interface, attribute or base class but I don't want to. Is there any way to enforce the constraints?

UPDATE: What I'm try to explain is to enforce constraints for example by namespace because having a string call IsValid is dumb and I only want certain set of model classes

like image 368
Jon Avatar asked Dec 06 '22 12:12

Jon


1 Answers

If you want to constrain it to just work on Person instances (and types derived from Person), you can do:

public static void IsValid<T>(this T parent) where T : Person

However, there is no reason to do this, as you can easily also write:

public static void IsValid(this Person parent)
like image 127
Reed Copsey Avatar answered Dec 17 '22 22:12

Reed Copsey