RogerInHawaii
New member
- Joined
- Aug 29, 2021
- Messages
- 1
- Programming Experience
- 10+
I want to have a function that takes an argument that is specifically a MassInGrams value and maybe even returns a MassInGrams value. Something like:
HOWEVER, that MassInGrams object should simply BE a float value, nothing more, nothing less.
I would hope that all I had to do was something like derive a MassInGrams class from a float, like:
But C# doesn't like that because float is a sealed type, you can't derive classes from sealed classes.
So how do I do what I want to do, which is to assure that the only values that are passed in to my function are MassInGrams type values and the only type of variables that can receive the return value from the function are also MassInGrams variables, and not simply any old type float value or float variable?
I encounter this type of issue over and over again, and I see functions defined by others that specify function arguments and return values that are simply floats or doubles or ints when in fact they represent specific characteristics, like the mass or velocity of an object. The only thing I've ever seen is that they just NAME the float variable accordingly, so you have something like:
or for a function:
but that in no way GUARANTEES that the value that's passed in is actually a MASS type value. You could just as easily do the following:
and then call :
which would make no sense but be perfectly compilable.
So how do I do what I want to do so that the programmer is required to pass in the right kind of values?
C#:
public MassInGrams MyMassManipulationFunction( MassInGrams theMassOfTheObject)
{
// ...
}
I would hope that all I had to do was something like derive a MassInGrams class from a float, like:
C#:
class MassInGrams : float
{
}
So how do I do what I want to do, which is to assure that the only values that are passed in to my function are MassInGrams type values and the only type of variables that can receive the return value from the function are also MassInGrams variables, and not simply any old type float value or float variable?
I encounter this type of issue over and over again, and I see functions defined by others that specify function arguments and return values that are simply floats or doubles or ints when in fact they represent specific characteristics, like the mass or velocity of an object. The only thing I've ever seen is that they just NAME the float variable accordingly, so you have something like:
C#:
float theMass;
C#:
public float MyMassManipulationFunction( float theMassOfTheObject )
C#:
float theNumberOfPeopleInTheBoat = 10;
C#:
MyMassManipulationFunction( theNumberOfPeopleInTheBoat );
So how do I do what I want to do so that the programmer is required to pass in the right kind of values?
Last edited by a moderator: