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
Namespaces in C# (and .Net overall) is pure syntactic sugar to make class names look shorter. As result of it what you want is “restrict generic by sub-string of full name of the class” which is not supported in C#.
As already suggested you may want to provide the method only for classes where it makes sense instead of doing other way around.