Related
Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).
We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &a=foo &b=bar.
The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?
Surprised no one mentioned C# 4.0 optional parameters that work like this:
public void SomeMethod(int a, int b = 0)
{
//some code
}
Edit: I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.
Another option is to use the params keyword
public void DoSomething(params object[] theObjects)
{
foreach(object o in theObjects)
{
// Something with the Objects…
}
}
Called like...
DoSomething(this, that, theOther);
In C#, I would normally use multiple forms of the method:
void GetFooBar(int a) { int defaultBValue; GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
// whatever here
}
UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:
public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender,
EDIVanInfo receiver,
EDIDocumentInfo info,
EDIDocumentType type
= new EDIDocumentType(EDIDocTypes.X12_814),
bool Production = false)
{
// My code is here
}
From this site:
https://www.tek-tips.com/viewthread.cfm?qid=1500861
C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:
using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
...
}
In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.
You could use method overloading...
GetFooBar()
GetFooBar(int a)
GetFooBar(int a, int b)
It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.
You could use Nullable types...
GetFooBar(int? a, int? b)
You could then check, using a.HasValue, to see if a parameter has been set.
Another option would be to use a 'params' parameter.
GetFooBar(params object[] args)
If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.
You can use optional parameters in C# 4.0 without any worries.
If we have a method like:
int MyMetod(int param1, int param2, int param3=10, int param4=20){....}
when you call the method, you can skip parameters like this:
int variab = MyMethod(param3:50; param1:10);
C# 4.0 implements a feature called "named parameters", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :)
An easy way which allows you to omit any parameters in any position, is taking advantage of nullable types as follows:
public void PrintValues(int? a = null, int? b = null, float? c = null, string s = "")
{
if(a.HasValue)
Console.Write(a);
else
Console.Write("-");
if(b.HasValue)
Console.Write(b);
else
Console.Write("-");
if(c.HasValue)
Console.Write(c);
else
Console.Write("-");
if(string.IsNullOrEmpty(s)) // Different check for strings
Console.Write(s);
else
Console.Write("-");
}
Strings are already nullable types so they don't need the ?.
Once you have this method, the following calls are all valid:
PrintValues (1, 2, 2.2f);
PrintValues (1, c: 1.2f);
PrintValues(b:100);
PrintValues (c: 1.2f, s: "hello");
PrintValues();
When you define a method that way you have the freedom to set just the parameters you want by naming them. See the following link for more information on named and optional parameters:
Named and Optional Arguments (C# Programming Guide) # MSDN
Hello Optional World
If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.
using System;
using System.Runtime.InteropServices;
using System.Reflection;
namespace ConsoleApplication1
{
public class Class1
{
public static void SayHelloTo([Optional, DefaultParameterValue("world")] string whom)
{
Console.WriteLine("Hello " + whom);
}
[STAThread]
public static void Main(string[] args)
{
MethodInfo mi = typeof(Class1).GetMethod("sayHelloTo");
mi.Invoke(null, new Object[] { Missing.Value });
}
}
}
I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.
public void Foo(int a, int b, int? c)
{
if(c.HasValue)
{
// do something with a,b and c
}
else
{
// do something with a and b only
}
}
optional parameters are for methods. if you need optional arguments for a class and you are:
using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example:
class myClass
{
public myClass(int myInt = 1, string myString =
"wow, this is cool: i can have a default string")
{
// do something here if needed
}
}
using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a "master constructor".
example:
class myClass
{
public myClass()
{
// this is the default constructor
}
public myClass(int myInt)
: this(myInt, "whatever")
{
// do something here if needed
}
public myClass(string myString)
: this(0, myString)
{
// do something here if needed
}
public myClass(int myInt, string myString)
{
// do something here if needed - this is the master constructor
}
}
The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.
Using overloads or using C# 4.0 or above
private void GetVal(string sName, int sRoll)
{
if (sRoll > 0)
{
// do some work
}
}
private void GetVal(string sName)
{
GetVal("testing", 0);
}
You can overload your method. One method contains one parameter GetFooBar(int a) and the other contain both parameters, GetFooBar(int a, int b)
You can use default.
public void OptionalParameters(int requerid, int optinal = default){}
For a larger number of optional parameters, a single parameter of Dictionary<string,Object> could be used with the ContainsKey method. I like this approach because it allows me to pass a List<T> or a T individually without having to create a whole other method (nice if parameters are to be used as filters, for example).
Example (new Dictionary<string,Object>() would be passed if no optional parameters are desired):
public bool Method(string ParamA, Dictionary<string,Object> AddlParams) {
if(ParamA == "Alpha" && (AddlParams.ContainsKey("foo") || AddlParams.ContainsKey("bar"))) {
return true;
} else {
return false;
}
}
Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.
i.e. Request.QueryString["a"]
This will decouple the leaf class from the factory / boilerplate code.
You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.
A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,
[WebMethod]
public string Foo(string arg1, XmlNode optarg2)
{
string arg2 = "";
if (optarg2 != null)
{
arg2 = optarg2.Value;
}
... etc
}
What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).
I have a web service to write that takes 7 parameters. Each is an optional query attribute to a sql statement wrapped by this web service. So two workarounds to non-optional params come to mind... both pretty poor:
method1(param1, param2, param 3, param 4, param 5, param 6, param7)
method1(param1, param2, param3, param 4, param5, param 6)
method 1(param1, param2, param3, param4, param5, param7)... start to see the picture. This way lies madness. Way too many combinations.
Now for a simpler way that looks awkward but should work:
method1(param1, bool useParam1, param2, bool useParam2, etc...)
That's one method call, values for all parameters are required, and it will handle each case inside it. It's also clear how to use it from the interface.
It's a hack, but it will work.
I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.
For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.
Optional Callback parameter:
public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
var isOnlyOne = lst.Count == 1;
if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
return isOnlyOne;
}
optional parameters are nothing but default parameters!
i suggest you give both of them default parameters.
GetFooBar(int a=0, int b=0) if you don't have any overloaded method, will result in a=0, b=0 if you don't pass any values,if you pass 1 value, will result in, passed value for a, 0 and if you pass 2 values 1st will be assigned to a and second to b.
hope that answers your question.
In the case when default values aren't available the way to add an optional parameter is to use .NET OptionalAttribute class - https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute?view=netframework-4.8
Example of the code is below:
namespace OptionalParameterWithOptionalAttribute
{
class Program
{
static void Main(string[] args)
{
//Calling the helper method Hello only with required parameters
Hello("Vardenis", "Pavardenis");
//Calling the helper method Hello with required and optional parameters
Hello("Vardenis", "Pavardenis", "Palanga");
}
public static void Hello(string firstName, string secondName,
[System.Runtime.InteropServices.OptionalAttribute] string fromCity)
{
string result = firstName + " " + secondName;
if (fromCity != null)
{
result += " from " + fromCity;
}
Console.WriteLine("Hello " + result);
}
}
}
You can try this too
Type 1
public void YourMethod(int a=0, int b = 0)
{
//some code
}
Type 2
public void YourMethod(int? a, int? b)
{
//some code
}
I have a number of 'jobs' in my application, where each job has a list of methods which it needs to call, along with it's parameters. Essentially a list containing the following object is called:
string Name;
List<object> Parameters;
So basically, when a job runs I want to enumerate through this list, and call the relevant methods. For example, if I have a method like the following:
TestMethod(string param1, int param2)
My method object would be like this:
Name = TestMethod
Parameters = "astring", 3
Is it possible to do this? I imagine reflection will be the key here.
Sure, you can do it like this:
public class Test
{
public void Hello(string s) { Console.WriteLine("hello " + s); }
}
...
{
Test t = new Test();
typeof(Test).GetMethod("Hello").Invoke(t, new[] { "world" });
// alternative if you don't know the type of the object:
t.GetType().GetMethod("Hello").Invoke(t, new[] { "world" });
}
The second parameter of Invoke() is an array of Object containing all the parameters to pass to your method.
Assuming the methods all belong to the same class, you could have a method of that class something like:
public void InvokeMethod(string methodName, List<object> args)
{
GetType().GetMethod(methodName).Invoke(this, args.ToArray());
}
If you're using .NET Framework 4, look at dynamic, otherwise GetMethod and then call Invoke of MethodInfo.
Use MethodBase.Invoke(). Should work down to .NET 2.0 with System.Reflection.
If you're using having to resort to reflection, there is probably a better way to accomplish your task. It may take a little more architecture, but it's doable.
Remember, having more code isn't a bad thing -- especially when it compliments the readability and manageability of your code. Reflection is difficult to understand for most, and you lose most of your compile time type safety. In your example, you could probably just get away with a switch statement and distinct objects for each method you were planning to call. e.g.
// Have some object hold the type of method it plans on calling.
enum methodNames
{
Method1,
Method2
}
...
class someObject
{
internal methodNames methodName {get; set;}
internal object[] myParams;
}
...
// Execute your object based on the enumeration value it references.
switch(someObject1.methodName)
{
case Method1:
Test.Method1(Int32.Parse(someObject1.myParams[0].ToString),someObject1.myParams[1].ToString());
break;
...
}
If you know that you only have a distinct set of method possibilities to call, why not just set yourself up ahead of time?
NuGet to the rescue! PM> Install-Package dnpextensions
Once you have that package in your project, all objects should now have a .InvokeMethod() extension, that will take the method name as a string and any number of parameters.
That does technically use "magic strings" for the method names, so if you wanted to strongly-type your method dictionary, you could make the keys of type MethodInfo and get them like this...
MethodInfo[] methodInfos = typeof(MyClass).GetMethods();
And then you can do something like this...
var methods = new Dictionary<MethodInfo, Object[]>();
foreach (var item in methods)
item.key.Invoke(null, item.value);
// 'null' may need to be an instance of the object that
// you are calling methods on if these are not static methods.
Or you could do some variation of the above block using the dnpextensions I mentioned earlier.
I'm trying to write a tool for serialization of values. And I was hoping to get some nice syntax working.....
float f = 9999.0f;
ByteSerializer s = new ByteSerializer ();
s.Write(f);
Where the params of Write() could be anything and any number:
public void Write (params dynamic[] objects)
{
for (int i =0;i<objects.Length;i++) {
byteList.AddRange (GetBytes (objects[i]));
}
}
GetBytes() should now be called according to the type of the object that was passed:
public byte[] GetBytes ( object v)
{
//Shouldn't actually do anything since it's a dummy
return new byte[0];
}
public byte[] GetBytes ( System.Single v)
{
//Why is this not called?
return BitConverter.GetBytes (v);
}
But it will always go straight for the method that takes an object as parameter.
I initially tried (params object[]) as method parameters and found this behaviour to be rather obvious. But why does dynamic[] behave the same?
objects[i].GetType() reports a System.Single so what's going on here? Is what I am trying to do just not possible?
There is no reason this shouldn't work with dynamic exactly as you described. One of the primary features of the DLR is to do at runtime what would have been done at compile time if the types had been known then. For example, the following program:
public class Program
{
public static void Main(string[] args)
{
WriteItems("a string", (byte)1, 3f, new object());
}
private static void WriteItems(params dynamic[] items)
{
foreach(dynamic item in items)
{
Write(item);
}
}
private static void Write(byte b)
{
Console.WriteLine("Write byte: {0}", b);
}
private static void Write(float f)
{
Console.WriteLine("Write Single: {0}", f);
}
private static void Write(string s)
{
Console.WriteLine("Write string: {0}", s);
}
private static void Write(object o)
{
Console.WriteLine("Write object: {0}", o);
}
}
Produces the output:
Write string: a string
Write byte: 1
Write Single: 3
Write object: System.Object
Method overloading relies on knowing at compile time the types of all the arguments. Here, you can't know the argument types at compile time - because it's dynamic - so the compiler uses the lowest common type - which is object. The difference between object and dynamic is that dynamic allows late binding syntax - but that doesn't help you here.
If you want to call GetBytes for the correct types, you need to use reflection. Specifically, you want to use GetMethod to find an overload of GetBytes that matches the type of each argument, and then call it. with Invoke. Something like this(not tested):
byteList.AddRange (GetType()
.GetMethod("GetBytes", new Type[objects[i].GetType()])
.Invoke(null, new object[objects[i]]));
The dynamic type behaves like the object type. The only difference is that for dynamic the compiler does no type checking (so you can avoid compiler errors when working e.g. with COM).
What you intend, can be done anyway. But you must take the long road and do an explicit typechecking/cast in your for loop (a long but simple switch/case construct).
HTH Thomas
Consider the following class
public class PlanetKrypton
{
public static void CallSuperManforHelp(string helpMessage, params object[] kryptonParams)
{
Console.WriteLine(String.Format(helpMessage,kryptonParams));
}
public static void CallSuperManforHelp(string helpMessage ,string sender,string senderZipCode)
{
Console.WriteLine("{0} from {1}. I am {2}", helpMessage, sender, senderZipCode);
}
}
public class ConsoleMan
{
public static void Main(string[] args)
{
string helpMessage = "I have a flat tire";
string sender = "Jerry";
int wrongZipType = 12345;
PlanetKrypton.CallSuperManforHelp(helpMessage, sender, wrongZipType);
PlanetKrypton.CallSuperManforHelp(helpMessage);
}
}
Now, if I have a more strongly typed method signature in the first method, I would have gotten a compile time error for both these method calls.
Are there any "best practices" for using params in method signature ?
Edit:Am making this a community wiki
I rarely see a need for it, myself.
If my function might need a collection of items, I make it take exactly that: ICollection<> or IEnumerable<>, potentially with an overload that takes a single T for that special case.
If the function is more utilitarian in nature (for example, I have a generic multi-field HashCode generating function), where params might seem to fit, I will still provide quite a few overloads for specific cases like 1 arg, 2 args, 3 args ... sometimes to 5 args or 10 args. Then I will add a catch-all with params. I do this because of the array object creation implicit with params.
I would avoid using params[] object. What I would do is create a class that encapsulates the three strings in your second overload:
public class HelpStuff
{
public string Message{get;set;}
public string Help{get;set;}
public string ZipCode{get;set;}
}
Then have two overloads like this:
public static void CallSuperManforHelp(string helpMessage, params string[] kryptonParams)
{
//do work
}
public static void CallSuperManforHelp(HelpStuff helpStuff)
{
//do work
}
Well, the obvious thing is that compile time errors are better than runtime errors. However, a flexible, usable API sometimes has to take precedence. I'd say in general you should only use arrays of Object, which lack compile time type safety and are sometimes inefficient, if you're sure there's no more static way to accomplish what you want.
If you have this method:
public static void CallSuperManforHelp(string helpMessage, params object[] kryptonParams) { ... }
you can cool it with these code:
CallSuperManforHelp("please help");
CallSuperManforHelp("please help", (object[])null);
These calling are equivalent. So if you overloading the "CallSuperManforHelp", you should think about calling convenction of these methods.
It's rarely needed, but useful at times - so I wouldn't say it's a best practice to avoid it. Just try to avoid ambiguity.
String.Format is of course the canonical example, and most cases where I use params, it's to pass to String.Format (e.g. a logging method).
Another example from the framework is DataRowCollection.Add: it's useful to be able to add field values without building an object array first:
DataTable myDataTable;
...
for(...)
{
myDataTable.Rows.Add(col1Value, col2Value, col3Value);
}
I wouldn't mix params/regular overloads in that way - I'd only generally use params to add an override that takes additional (unknown at compile time) parameters.
e.g. A normal method, and then one that takes an additional params:
public static void CallSuperManforHelp(string helpMessage);
public static void CallSuperManforHelp(string helpMessage, params object[] kryptonParams);
This eliminates the ambiguity between the overloads.
If you want the two methods you have defined, then you could simply give them different names to avoid any ambiguity and clarify their usage:
public static void CallSuperManforHelpFormatted(string helpMessage, params object[] kryptonParams)
public static void CallSuperManforHelp(string helpMessage ,string sender,string senderZipCode)
My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:
Class test<T>{
int method1(Obj Parameter1){
//in here I want to do something which I would explain as
T.TryParse(Parameter1);
//my problem is that it does not work ... I get an error.
//just to explain: if I declare test<int> (with type Integer)
//I want my sample code to call int.TryParse(). If it were String
//it should have been String.TryParse()
}
}
So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!
Edit: Thank you all for your answers!
Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.
This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)
Though if you have some other suggestion I am still waiting (and willing to participate)
The problem is that TryParse isn't defined on an interface or base class anywhere, so you can't make an assumption that the type passed into your class will have that function. Unless you can contrain T in some way, you'll run into this a lot.
Constraints on Type Parameters
Short answer, you can't.
Long answer, you can cheat:
public class Example
{
internal static class Support
{
private delegate bool GenericParser<T>(string s, out T o);
private static Dictionary<Type, object> parsers =
MakeStandardParsers();
private static Dictionary<Type, object> MakeStandardParsers()
{
Dictionary<Type, object> d = new Dictionary<Type, object>();
// You need to add an entry for every type you want to cope with.
d[typeof(int)] = new GenericParser<int>(int.TryParse);
d[typeof(long)] = new GenericParser<long>(long.TryParse);
d[typeof(float)] = new GenericParser<float>(float.TryParse);
return d;
}
public static bool TryParse<T>(string s, out T result)
{
return ((GenericParser<T>)parsers[typeof(T)])(s, out result);
}
}
public class Test<T>
{
public static T method1(string s)
{
T value;
bool success = Support.TryParse(s, out value);
return value;
}
}
public static void Main()
{
Console.WriteLine(Test<int>.method1("23"));
Console.WriteLine(Test<float>.method1("23.4"));
Console.WriteLine(Test<long>.method1("99999999999999"));
Console.ReadLine();
}
}
I made a static dictionary holding a delegate for the TryParse method of every type I might want to use. I then wrote a generic method to look up the dictionary and pass on the call to the appropriate delegate. Since every delegate has a different type, I just store them as object references and cast them back to the appropriate generic type when I retrieve them. Note that for the sake of a simple example I have omitted error checking, such as to check whether we have an entry in the dictionary for the given type.
To access a member of a specific class or interface you need to use the Where keyword and specify the interface or base class that has the method.
In the above instance TryParse does not come from an interface or base class, so what you are trying to do above is not possible. Best just use Convert.ChangeType and a try/catch statement.
class test<T>
{
T Method(object P)
{
try {
return (T)Convert.ChangeType(P, typeof(T));
} catch(Exception e) {
return null;
}
}
}
One more way to do it, this time some reflection in the mix:
static class Parser
{
public static bool TryParse<TType>( string str, out TType x )
{
// Get the type on that TryParse shall be called
Type objType = typeof( TType );
// Enumerate the methods of TType
foreach( MethodInfo mi in objType.GetMethods() )
{
if( mi.Name == "TryParse" )
{
// We found a TryParse method, check for the 2-parameter-signature
ParameterInfo[] pi = mi.GetParameters();
if( pi.Length == 2 ) // Find TryParse( String, TType )
{
// Build a parameter list for the call
object[] paramList = new object[2] { str, default( TType ) };
// Invoke the static method
object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList );
// Get the output value from the parameter list
x = (TType)paramList[1];
return (bool)ret;
}
}
}
// Maybe we should throw an exception here, because we were unable to find the TryParse
// method; this is not just a unable-to-parse error.
x = default( TType );
return false;
}
}
The next step would be trying to implement
public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args );
With full parameter type matching etc.
This isn't really a solution, but in certain scenarios it could be a good alternative: We can pass an additional delegate to the generic method.
To clarify what I mean, let's use an example. Let's say we have some generic factory method, that should create an instance of T, and we want it to then call another method, for notification or additional initialization.
Consider the following simple class:
public class Example
{
// ...
public static void PostInitCallback(Example example)
{
// Do something with the object...
}
}
And the following static method:
public static T CreateAndInit<T>() where T : new()
{
var t = new T();
// Some initialization code...
return t;
}
So right now we would have to do:
var example = CreateAndInit<Example>();
Example.PostInitCallback(example);
However, we could change our method to take an additional delegate:
public delegate void PostInitCallback<T>(T t);
public static T CreateAndInit<T>(PostInitCallback<T> callback) where T : new()
{
var t = new T();
// Some initialization code...
callback(t);
return t;
}
And now we can change the call to:
var example = CreateAndInit<Example>(Example.PostInitCallback);
Obviously this is only useful in very specific scenarios. But this is the cleanest solution in the sense that we get compile time safety, there is no "hacking" involved, and the code is dead simple.
Do you mean to do something like this:
Class test<T>
{
T method1(object Parameter1){
if( Parameter1 is T )
{
T value = (T) Parameter1;
//do something with value
return value;
}
else
{
//Parameter1 is not a T
return default(T); //or throw exception
}
}
}
Unfortunately you can't check for the TryParse pattern as it is static - which unfortunately means that it isn't particularly well suited to generics.
The only way to do exactly what you're looking for would be to use reflection to check if the method exists for T.
Another option is to ensure that the object you send in is a convertible object by restraining the type to IConvertible (all primitive types implement IConvertible). This would allow you to convert your parameter to the given type very flexibly.
Class test<T>
{
int method1(IConvertible Parameter1){
IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));
T temp = Parameter1.ToType(typeof(T), provider);
}
}
You could also do a variation on this by using an 'object' type instead like you had originally.
Class test<T>
{
int method1(object Parameter1){
if(Parameter1 is IConvertible) {
IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));
T temp = Parameter1.ToType(typeof(T), provider);
} else {
// Do something else
}
}
}
Ok guys: Thanks for all the fish. Now with your answers and my research (especially the article on limiting generic types to primitives) I will present you my solution.
Class a<T>{
private void checkWetherTypeIsOK()
{
if (T is int || T is float //|| ... any other types you want to be allowed){
return true;
}
else {
throw new exception();
}
}
public static a(){
ccheckWetherTypeIsOK();
}
}
You probably cant do it.
First of all if it should be possible you would need a tighter bound on T so the typechecker could be sure that all possible substitutions for T actually had a static method called TryParse.
You may want to read my previous post on limiting generic types to primitives. This may give you some pointers in limiting the type that can be passed to the generic (since TypeParse is obviously only available to a set number of primitives ( string.TryParse obviously being the exception, which doesn't make sense).
Once you have more of a handle on the type, you can then work on trying to parse it. You may need a bit of an ugly switch in there (to call the correct TryParse ) but I think you can achieve the desired functionality.
If you need me to explain any of the above further, then please ask :)
Best code: restrict T to ValueType this way:
class test1<T> where T: struct
A "struct" here means a value type.
String is a class, not a value type.
int, float, Enums are all value types.
btw the compiler does not accept to call static methods or access static members on 'type parameters' like in the following example which will not compile :(
class MyStatic { public static int MyValue=0; }
class Test<T> where T: MyStatic
{
public void TheTest() { T.MyValue++; }
}
=> Error 1 'T' is a 'type parameter', which is not valid in the given context
SL.
That is not how statics work. You have to think of statics as sort of in a Global class even if they are are spread across a whole bunch of types. My recommendation is to make it a property inside the T instance that can access the necessary static method.
Also T is an actual instance of something, and just like any other instance you are not able to access the statics for that type, through the instantiated value. Here is an example of what to do:
class a {
static StaticMethod1 ()
virtual Method1 ()
}
class b : a {
override Method1 () return StaticMethod1()
}
class c : a {
override Method1 () return "XYZ"
}
class generic<T>
where T : a {
void DoSomething () T.Method1()
}