Luke101
Luke101

Reputation: 65238

How to use the AS keyword with unknown type

I am trying to use the AS keyword with an unknown type. Here is my code:

public GetData(Type MyType, string CSVPath)
{
    var engine = new FileHelperEngine(MyType);

    try
    {
        _Data = engine.ReadFile(CSVPath) as MyType;  //error here
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error occured: " + ex.Message);
    }
}

as you can see in this code I am getting an error were MyType is. Is there a better way to do this

Upvotes: 1

Views: 137

Answers (3)

Jeremy Pridemore
Jeremy Pridemore

Reputation: 1995

Here's a class that does this, though I have a hard time thinking of a good case for a dynamic cast like this.:

using System;

namespace Test
{
    class Program
    {
        private object _data;

        static void Main(string[] args)
        {
            new Program().EntryPoint();
        }

        public void EntryPoint()
        {
            GetData(typeof(string), "Test");
            Console.WriteLine(_data);
        }

        public void GetData(Type myType, string csvPath)
        {
            var engine = new FileHelperEngine(myType, csvPath);

            // This is the line that does it.
            _data = Convert.ChangeType(engine.ReadFile(csvPath), myType);
        }

        private class FileHelperEngine
        {
            public string Value { get; set; }
            public FileHelperEngine(Type t, string value) { Value = value.ToString(); }

            public string ReadFile(string path) { return Value; }
        }
    }
}

Upvotes: 0

wsanville
wsanville

Reputation: 37516

Use a generic method instead of passing in a Type as a parameter:

public void GetData<T>(string CSVPath)
{
    var engine = new FileHelperEngine(typeof(T));
    _Data = engine.ReadFile(CSVPath) as T;
    if (_Data != null)
    {
        //correct type, do the rest of your stuff here
    }
}

Upvotes: 3

zmbq
zmbq

Reputation: 39013

I'm not sure I understand. First, using as doesn't throw an exception, it just returns null.

Second, I'm pretty sure you don't want to cast, you just want to check the type, so you need the is operator. But since MyType is only known at runtime, you indeed need reflection. It's quite simple:

object o = engine.Readfile(CSVPath);
if(MyType.IsAssignableFrom(o.GetType())
    _Data = o;
else
    Console.WriteLine("Mismatching types: {0} is not of type {1}", o.GetType(), MyType);

Note: I'm assuming _Data is of type object, otherwise, you just use the as operator with _Data's type.

Upvotes: 1

Related Questions