-3

Can someone help me to see why my condition is not working? To get more clear, i wish get a T type and see if this type is a string[]. In my code bellow is not matching the types, anyone can say to me what i doing wrong?

public T GetTotalMemoryValue<T>()
{
    object result = null;
    result = typeof(T);

    if(result.GetType() == typeof(string[]))
    {
        Convert.ChangeType(result, typeof(string[]));

        try
        {  
          ...
        }
        return (T)(object) buffer;

    }
}

buffer is a string array.

  • 2
    For one, you're not returning a value... is that what you mean by "always failing"? How is the code even compiling? – Broots Waymb Jul 11 '17 at 20:18
  • what do you want to achieve? What is the error? – Iqon Jul 11 '17 at 20:19
  • This snippet doesn't compile at the moment, do you need help to make it compile or run? Please post a [update your question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) to help us understand your problem better. – DaveShaw Jul 11 '17 at 20:22
  • There is no return statement, how it is possible pass the compiling – Huan Jiang Jul 11 '17 at 20:23
  • Giving this a read may help: https://stackoverflow.com/questions/5737840/whats-the-difference-between-system-type-and-system-runtimetype-in-c – Broots Waymb Jul 11 '17 at 20:23
  • you're essentially calling `typeof(something).GetType()`, which AFAIK will always return System.RuntimeType for any type `something`. So why do you expect it to be equal to `typeof(string[])` – Joe Jul 11 '17 at 20:23
  • It seems the code you provided is incomplete; it will not compile since where are no return statement in `GetTotalMemoryValue()`. – Pavel Dmitrenko Jul 11 '17 at 20:24
  • I whant see if T type is string array. if it is get moving with code. – Jefferson Puchalski Jul 11 '17 at 20:24
  • I dont put the rest of code, but i will fill with my return part. – Jefferson Puchalski Jul 11 '17 at 20:26

1 Answers1

1

As i do not know what you really want to achieve, here why the comparison is failing:

var result = typeof(T); // is the same as below
Type result = typeof(T);

typeof() will return a Type and Type.GetType() will always return Type.

The correct comparison would be:

if(typeof(T) == typeof(string[]) 
{
    // code goes here
}
Iqon
  • 1,920
  • 12
  • 20
  • Not quite. typeof(string[]) is returning a System.String[] and result.GetType() is returning a System.RuntimeType. – Broots Waymb Jul 11 '17 at 20:30
  • Thanks @DangerZone i got fixed using your example. I didint repair the 2 returning types. – Jefferson Puchalski Jul 11 '17 at 20:32
  • Partly. ```GetType``` will return a ```RuntimeType```, but ```typeof()``` returns also an ```RuntimeType``` containing information about the type ```string[]``` (or ```System.String[]```) – Iqon Jul 11 '17 at 20:33