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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With