whytheq
whytheq

Reputation: 35577

Variant Type in C#

VBA (and I assume VB) has a Variant type which I believe takes up more memory, but covers various data types.

Is there an equivalent in c# ?

In a windows form say I had the following, how would I amend the type of z so that it runs ok

    private void uxConvertButton_Click(object sender, EventArgs e)
    {
        int x = 10;

        byte j = (byte)x;
        upDateRTB(j);

        long q = (long)x;
        upDateRTB(q);

        string m = x.ToString();
        upDateRTB(m);
    }

    void upDateRTB(long z) {
        MessageBox.Show(this,"amount; "+z);
    }

Upvotes: 8

Views: 64348

Answers (5)

Me.Name
Me.Name

Reputation: 12544

An object parameter would accept all, but if you'd like to keep the variables strongly typed (and avoid boxing in the process), you could use generics:

void upDateRTB<T>(T z) {
    MessageBox.Show(this,"amount; "+ Convert.ToString(z)); 
}

The method calls could remain precisely the same, because the compiler can resolve the generic type based on the given parameter.

Upvotes: 8

Petar Ivanov
Petar Ivanov

Reputation: 93060

"amount; "+z implicitly calls the ToString method on z. So you can use type object:

void upDateRTB(object z) {
    MessageBox.Show(this,"amount; "+z);
}

You can also use dynamic, but I don't see the point:

void upDateRTB(dynamic z) {
    MessageBox.Show(this,"amount; "+z);
}

Upvotes: 3

Ribtoks
Ribtoks

Reputation: 6922

If you're talking about "variant" type in c#, take a look at dynamic type in .net 4.0

But for solving your task it would be enough to use z.ToString() in your MessageBox.Show

Upvotes: 7

Emond
Emond

Reputation: 50682

The dynamic keyword or the object type could give you the variant behavior you want but:

In this case I'd change the function to:

void upDateRTB(string z) {
    MessageBox.Show(this,"amount; " + z);
}

Because that's all the method needs.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039200

void upDateRTB(object z) {
    MessageBox.Show(this, "amount; " + Convert.ToString(z));
}

Upvotes: 13

Related Questions