Home > other >  Any way to add custom type modifiers to either c# or c ?
Any way to add custom type modifiers to either c# or c ?

Time:03-26

I want to be able to use this syntax here:

public enclosed int num = {0, 5, 10};

this code would clamp the int num from 0 to 10, with a starting value of 5.

you could make a class that handles this, but it would be a lot of extra effort for a sort of convoluted solution, and I'm wondering if there is a way to somehow to do it just in a variable declaration, sort of like declaring an unsigned int, I want to be able to declare an enclosed int.

CodePudding user response:

No, this is exactly what classes and structs are for, so that you can create your own types with these sorts of behaviors. But these are compiled languages, so the syntax is fixed. In C you might be able to do something using macros, but that's a preprocessor thing.

CodePudding user response:

I got pretty close :P

public class enclosed<T> {
    private T min {get;}
    private T max {get;}
    private T val {get;}
    
    public enclosed(T min, T val, T max)
    {
        ...
    }
}

Now you can use it like this:

public enclosed<int> num = new(0, 5, 10);

vs

public enclosed int num = {0, 5, 10};
  • Related