How to create custom syntax for describing an object in C #?

Search:

And I don’t remember ...


Preconception: Each "built-in type" in C # (for example, int , float , char , etc.) is a class, and each class in C # inherits from Object . Therefore, each "built-in type" is inherited from the Object class.

Given this prejudice, I would suggest that to set the double variable, for example, I would need to set some properties using the "normal" syntax. Here is what I mean:

 double number = new double(); number.leftSide= 5; number.rightSide = 23; Console.Write(number); // Output: // 5.23 

But C # has a special equivalent syntax for creating a double variable (so that it will do what I tried to do above, and not that the code above will actually work):

 double number = 5.23; 

The compiler understands that a floating point divides the number into two: 5 and 23.

My question is, can I do the same with my own classes. For example, if I have my own Time class (and this is just an example, so please do not suggest using the built-in time classes), I would like to be able to instantiate it as follows:

 Time time = 10:25; 

And the compiler will understand that the colon divides the number into hours and minutes (which, I assume, are the properties that I need to create in the Time class).

I heard about Roslyn CTP , but I'm looking for a simpler, in-line way to accomplish what I described.

Can I do it?

+5
source share
2 answers

In C #, this is not possible. The closest thing you can do is define an implicit conversion from string to Date . for instance

 public class Time { public static implicit operator Time(string value) { // Initialize your object with value // Similar to var values = value.Split(':'); var hour = Convert.ToInt32(values[0]); var min = Convert.ToInt32(values[1]); . . . } . . . // Your fields, properties and methods } 

It will allow you

 Time time = "10:25"; 
+8
source

My question is, can I do the same with my own classes.

No, you can’t. C # does not support custom syntax constructs. You must live with a set of language functions, such as syntax constructs, operators, etc., defined by the language.

Each "built-in type" in C # (such as int, float, charetc.) Is a class, and each class in C # inherits from the Object class.

Primitive types (such as int , float , etc.) are not classes. These are primitive types. To support object-oriented functions, such as methods, the language defines a struct (for example, Int32 , Single ), which is the "look" of shadow primitive types.

That everything can be an Object , in the case of primitive types achieved through boxing, is a process that takes a primitive value type and creates a wrapped object around it.

+3
source

All Articles