I have such class where all properties must be nullable types. Is it possible to add design(not runtime) time validation for Sessions class properties to check is added new property has nullable type? The compiler should give error and not compile code if property will not have nulable type.
public class Sessions : SessionInfo<Sessions>
{
public int? UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string OldEmail { get; set; }
public bool? UserManager { get; set; }
public bool? UserManagerVisible { get; set; }
public bool? TransactionCall { get; set; }
}
At first, you are slightly incorrect because in your example only
int?andbool?properties are nullable.Stringis a reference type, it can acceptnull(like any reference type) but it isn’t nullable per se (in the C# sense of the word).Secondly, no, there isn’t any way to “check” the class definition at compile type and frankly it doesn’t make any sense to me. Do you expect this restriction to be coded somewhere? So what if you decide to drop it eventually? Would you change this “constraining” code? But then what is the point of the restriction if it can be lifted by just editing the code? It’s much like installing a lock on the door only to keep keys in it.
Yes, you can work around this by using a static analyzer tool like FxCop, as suggested by Anders, but from my point of view the very need for this highlights a design problem in your code. Such rules are usually created to enforce certain design policy on the project level, not to constrain a single class in your code.
I’m curious about the role of
SessionInfo<T>. Does it go over each property with Reflection? If you explained your original problem, we could help you come up with a better solution. The use of Curiously Recurring Template Pattern also suggests that you may be the type of person to oversolve the problems.What are you trying to accomplish?