When passing a class as a parameter of a function, can a property of that class be marked as required during build time?
I want to be able to set a class as a parameter of a method, like this:
public DoThing(MyClass class)
{
//TODO: do thing
}
But I also want some of the properties of the class to be required. I can check those properties and throw an error or something during runtime, but I was wondering if it were possible to declare some of those properties required during build time.
I can always list out the parameters, but I like using classes to make the code easier to read. Is this possible or do I just have to do runtime checks?
To clarify, I wanted to make something like this, less ambiguous:
DoThing(true, true, null, true);
At a glance, I can't see what those properties are. So normally I'd make it a class and set the values like this:
var myClass = new MyClass()
{
IsDone = true,
IsNotDone = null,
CouldItBeDone = false,
IfNotDone = true
};
DoThing(myClass);
As I'm reading the code, I can easily see the name of the properties and that gives me an idea of what I'm looking at. But if IsNotDone
cannot be null, there's no way I know of to check that during build time. I'd have to do a null check during runtime.
Solution 1:
It seems that what you are trying to do will be solved neatly by named arguments, without the use of a helper class.
Just call your function like this, giving explicit argument names:
DoThing(quickly: true, silently: true, why: null, verbose: true);
You can pass named arguments in any order.