Gokul E
Gokul E

Reputation: 1386

What is basic Difference Between Type.GetType() and Type.GetElementType()

I can understand the Type.GetType() 's Scenario which the Object's type will be got, but what is Type.GetElementType() and what does it do?

Can anyone explain it in a clear way?

Upvotes: 1

Views: 847

Answers (3)

chridam
chridam

Reputation: 103365

Type.GetElementType gets the Type of the object encompassed or referred to by the current array, pointer or reference type. For example:

using System;
class TestGetElementType 
{
    public static void Main() 
    {
        int[] array = {1,2,3};
        Type t = array.GetType();
        Type t2 = t.GetElementType();
        Console.WriteLine("The element type of {0} is {1}.",array, t2.ToString());
        TestGetElementType newMe = new TestGetElementType();
        t = newMe.GetType();
        t2 = t.GetElementType();
        Console.WriteLine("The element type of {0} is {1}.", newMe, t2==null? "null" : t2.ToString());
    }
}

Outputs:

The element type of System.Int32[] is System.Int32.
The element type of TestGetElementType is null.

Upvotes: 2

Rohit Vyas
Rohit Vyas

Reputation: 1969

GetElementType is for use with arrays, not other generic classes

For more detail Refer This link

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500495

Type.GetElementType is used for arrays, pointers, and by-ref parameter types. For example:

object value = new int[100];
Console.WriteLine(value.GetType()); // System.Int32[]
Console.WriteLine(value.GetType().GetElementType()); // System.Int32

Or:

public void Foo(ref int x) {}
...
var method = typeof(Test).GetMethod("Foo");
var parameter = method.GetParameters()[0];
Console.WriteLine(parameter.ParameterType); // System.Int32&
Console.WriteLine(parameter.ParameterType.GetElementType()); // System.Int32

As for when you'd use them - well, it depends what you're using reflection for to start with.

Upvotes: 9

Related Questions