user1225775
user1225775

Reputation: 253

C#: Declaring a constant variable for datatype to use

Is it possible somehow to define a constant that says what datatype to use for certain variables, similar to generics? So in a certain class I would have something like the following:

MYTYPE = System.String;

// some other code here

MYTYPE myVariable = "Hello";

From the principle it should do the same as generics but I don't want to write the datatype every time the constructor for this class is called. It should simply guarantee that for two (or more) variables the same datatype is used.

Upvotes: 5

Views: 298

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1502816

Well, you can use a using directive:

using MYTYPE = System.String;

However, that isn't really like a typedef - in particular, this code is now perfectly valid:

MYTYPE x = "hello";
string y = "there";
x = y;

The compiler knows they're still the same type.

It's not really clear what you're trying to achieve, particularly here:

I don't want to write the datatype every time the constructor for this class is called.

What do you mean?

Note that using directives are specific to a source file, not to a whole project.

Upvotes: 7

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

You could use an alias:

using System;
using MYTYPE = System.String;

class Program
{
    static void Main()
    {
        MYTYPE f = "Hello";
        Console.WriteLine(f);
    }
}

Upvotes: 2

user555045
user555045

Reputation: 64913

Yes, with a using alias directive.

edit: beaten by a couple of seconds..

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063774

You can do that with a using alias:

using MyType = System.String;

however, only on a per-file basis. Frankly, it is useful for making a short alias to some complex composite generic type (I'm thinking of "Owin" etc), but other than that, generics are more versatile.

Upvotes: 4

Related Questions