user813039
user813039

Reputation: 21

How to pass dynamic data types as parameters in C#?

I have a method in c# which builds xml on the fly.

However, I won't know the specific elements/attributes until run-time.

How do I declare parameters when I don't know what the data-types, names and values or amount will be?

Upvotes: 2

Views: 1449

Answers (3)

aligray
aligray

Reputation: 2832

Another option is to use generics. This will be helpful if you need to put constraints on the types that can be passed in:

public void BuildXml<T>(T obj)
{
    // do work
}

Or if you are expecting a collection of objects:

public void BuildXml<T>(IEnumerable<T> items)
{
    // do work
}

Then you can use reflection to get the relevant data you need.

Upvotes: 0

Igby Largeman
Igby Largeman

Reputation: 16747

You can use System.Object for all parameters, since it is the base class for all other types. You can then find out the actual declared type with the GetType() method, and treat the value appropriately.

e.g.

if (myParam.GetType() == typeof(Int32)) 
{
   // treat value as integer ...
   int val = (int)myParam;
}

or you can use the syntax

if (myParam is Int32)
{
   // treat value as integer ...
   int val = (int)myParam;
}
else if (myParam is String)
{
   string val = myParam.ToString();
}

etc.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133072

You are looking for params keyword. Or are you? :)

Upvotes: 2

Related Questions