Possible ?

  • Thread starter Thread starter Jarod
  • Start date Start date
J

Jarod

Hey
I would like to write a function that returns type given as argument so it
would be likethis:

public GivenType GetFromSomeWhere(object sth, Type givenType)
{
return (givenType) sth;
}

Is it possible to write function that works like above ( it won't work now
;) But I hope you understand what I need.
Jarod
 
You mean new instance of given Type?

public T GetT<T>()
{
return Activator.CreateInstance<T>();
}

without generics:

public object GetInstance(Type aType)
{
return Activator.CreateInstance(aType);
}

Or do you mean casting the object passed as argument to the given Type?

public object Cast(object from, Type to)
{
return from;
}

This is it. It makes no sense to have a method performing a cast. You can
(and should) do the cast yourself in the code, not have a method to do it.
If you want to get generic, it's possible to write what you need as generic
method, but it's, ehm...dumb.

public T CastToT<T>(object from)
{
return (T)from;
}
 
public T CastToT said:
{
return (T)from;
}

That's great ;) But I don't use it for casting. I have DataRow and I need
data from it for my properites so it's easier to use GetData<int>(ref myRow,
"SomeField");
But I want to go futher ;) So how to make function that returned typed is
set by function when it works. So in this case it should read the
column.DataType for given fieldName, and set apropriate returned type and
cast to such type.
So code would look like this:

someType GetData(DataRow row, string fieldName)
{
someType = row.Table.Columns[fieldName].DataType;
if ( not null and so on);
return (someType) row[fieldName];
}

Jarod
 
As you may know, methods are compiled at compile time. So you can not change
return types of methods at run time.

Jarod said:
public T CastToT<T>(object from)
{
return (T)from;
}

That's great ;) But I don't use it for casting. I have DataRow and I need
data from it for my properites so it's easier to use GetData<int>(ref
myRow, "SomeField");
But I want to go futher ;) So how to make function that returned typed is
set by function when it works. So in this case it should read the
column.DataType for given fieldName, and set apropriate returned type and
cast to such type.
So code would look like this:

someType GetData(DataRow row, string fieldName)
{
someType = row.Table.Columns[fieldName].DataType;
if ( not null and so on);
return (someType) row[fieldName];
}

Jarod
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top