Reputation: 1
The main difference between built-in data types and user defined data types is that: built-in data types can accept literal values(values inserted into code directly,this process is also know as hard-codding).
So is it possible create custom data type same as boolean which accepts three values: yes/no/maybe WITHOUT USING enums.
such as following code:
MyCustomBoolean a = maybe;
I asked above question because i want to understand that built-in data types in C# are instructed in Core Language(such as C++ int,char...) or no?
---Update---
for the second question,let me ask a question to make the 2nd question more clear:
I know that for example string is alias of System.String but does pure string in C# works without System.String?
Upvotes: 0
Views: 453
Reputation: 10708
There are no ways to do this exactly as you've requested. You can however create constant fields in C# which can accomplish this result (named values) but only with the integral types or strings - in other words, the things you can already use for compile-time constants. This can be particularly useful for otherwise Magic Values.
public const string Maybe = "Maybe";
public const int Maybe = 0;
One way around this, though it will not be usable as a true constant, is to initialize static readonly fields or properties. For example
public static readonly MyCustomBoolean Maybe { get { return new MycustomBoolean(); } }
public static MyCustomBoolean Maybe = new MyCustomBoolean();
Upvotes: 2
Reputation: 38364
Literals are a feature of the C# language. You cannot create new literals.
You might be interested in a different programming language such as Nemerle that allows you to create user defined literals such as this XML literal: https://github.com/rsdn/nemerle/wiki/XML-literals
Enums and constants usually fill the void for C#. For more complex structures you often see some flavor of fluent API being used.
Of course we can see the lack of this feature in C# meant that to provide a natural way to define queries meant the C# language spec needed to change to support LINQ. Had C# had similar meta programming features as Nemerle, then they could have accomplished the same goals as LINQ without changing the language syntax.
Upvotes: 0
Reputation: 1845
You can have a nullable bool instead for this specific case. With typical operations like:
bool? b = null
if (b.HasValue)
if (b.Value)
b = true
Where the maybe would be null, or having HasValue == false
.
Upvotes: 0