Variable Return Method Type in C #

I want to give a parameter to a method, and I want my method to return data by looking at the parameter. The data can be in the form of Boolean, string, int, etc. How can I return the type of a variable from a method? I do not want to return the type of the object, and then pass it to another type. For example:

BlaBla VariableReturnExampleMethod(int a) { if (a == 1) return "Demo"; else if (a == 2) return 2; else if (a == 3) return True; else return null; } 

The reason I want this is because there is a method that reads the selected row column from the database. The column types do not match, but I have to return every column information.

+7
source share
6 answers

How can I return the type of a variable from a method? I do not want to return the type of the object, and then pass it to another type.

Good thing is basically what you need to do. Alternatively, if you use C # 4, you can make the return type dynamic , which will allow you to do an implicit conversion:

 dynamic VariableReturnExampleMethod(int a) { // Body as per question } ... // Fine... int x = VariableReturnExampleMethod(2); // This will throw an exception at execution time int y = VariableReturnExampleMethod(1); 

You basically specify types so that the compiler knows what to expect. How can this work if the type is known only at runtime? The reason the dynamic version works is because it basically tells the compiler to postpone its normal work until runtime - so you lose the normal security that would allow the second example to exit at compile time.

+13
source

Use the dynamic Keyword instead of BlahBlah if you are targeting .Net 4.0 but if less, then object is your safest bet because it is the base class for every other class you can think of.

+4
source

This seems like a good example for generics . If you know what type of data you expect when you call it, you can call this specific generic version of the function.

+2
source

Think about using something like Dapper-dot-net (written by Mark Gravell and Sam Shaffron in our own stack overflow) to pull things out of the database. It processes the database to match objects for you.

Also, if you don’t want to use the tool, and you are extracting from the database, and you know the data types of the various columns at compile time (as it sounds, you are doing), you should probably be working on rows, not on columns .

 //Pseudo-code: List<DatabaseObject> objects = new List<DatabaseObject>(); foreach(var row in DatabaseRows) { var toAdd = new DatabaseObject(); toAdd.StringTypeVariable = "Demo"; toAdd.IntTypeVariable = 2; toAdd.BoolTypeVariable = true; object.Add(toAdd); } 

Note: you can use the object initializer and linq syntax here, but this is the easiest way I could think of demonstrating this without using a ton of additional material.

Also note that here I am assuming that you really do not want to return "Demo", 2 and true, but values ​​that use a string. This means that you would change the hard-coded values: row.GetStringType(stringColumnIdx) or something like that.

+2
source

Use the return type as object , then you can get any type of return. You must process return type ether through reflection or another method.

check this:

 void Main() { object aa = VariableReturnExampleMethod(3); Console.WriteLine(aa.ToString()); } object VariableReturnExampleMethod(int a) { if (a == 1) return "Demo"; else if (a == 2) return 2; else if (a == 3) return true; else return null; } 

Edit: I am in favor of strongly typed objects, and you can easily implement it on the .net platform.

 if(returnedValue !=null) { string currentDataType = returnedValue.GetType().Name; object valueObj = GetValueByValidating(currentDataType, stringValue); } public object GetValueByValidating(string strCurrentDatatype, object valueObj) { if (valueObj != "") { if (strCurrentDatatype.ToLower().Contains("int")) { valueObj = Convert.ToInt32(valueObj); } else if (strCurrentDatatype.ToLower().Contains("decimal")) { valueObj = Convert.ToDecimal(valueObj); } else if (strCurrentDatatype.ToLower().Contains("double") || strCurrentDatatype.ToLower().Contains("real")) { valueObj = Convert.ToDouble(valueObj); } else if (strCurrentDatatype.ToLower().Contains("string")) { valueObj = Convert.ToString(valueObj); } else { valueObj = valueObj.ToString(); } } else { valueObj = null; } return valueObj; } 
0
source

I look at your requests, and one is better than the second, but the last time I have to rewrite in order to better understand the solution. And this solution missed the long, if something else stack, and replaced its foreach with an enumeration of types, where we can implement all the types that we need. I prefer using dynamic, but it can also be used.

The main function GetValueByValidating return value, if the type is defined and possible, otherwise returns false Look niranjan-kala , this is your main function after overwriting.

 /// /// Enum of wanted types /// public enum Types { [ExtendetFlags("int")] INT, [ExtendetFlags("decimal")] DECIMAL, [ExtendetFlags("double")] DOUBLE, [ExtendetFlags("real")] REAL, [ExtendetFlags("string")] STRING, [ExtendetFlags("object")] OBJECT, [ExtendetFlags("null")] NULLABLE } /// /// Cycle by types when in enum exist string reference on type (helper) /// /// /// public static Types GetCurrentType(string container) { foreach (Types t in Enum.GetValues(typeof(Types))) { if (container.Contains(t.GetFlagValue())) { return t; } } return Types.NULLABLE; } /// /// Return object converted to type /// /// /// /// public static object GetValueByValidating(string strCurrentDatatype, object valueObj) { var _value = valueObj != null ? valueObj : null; try { Types _current = _value != null ? GetCurrentType(strCurrentDatatype.ToLower()) : Types.NULLABLE; switch (_current) { case Types.INT: valueObj = Convert.ToInt32(valueObj); break; case Types.DECIMAL: valueObj = Convert.ToDecimal(valueObj); break; case Types.DOUBLE: valueObj = Convert.ToDouble(valueObj); break; case Types.REAL: valueObj = Convert.ToDouble(valueObj); break; case Types.STRING: valueObj = Convert.ToString(valueObj); break; case Types.OBJECT: break; case Types.NULLABLE: throw new InvalidCastException("Type not handled before selecting, function crashed by retype var."); } } catch (InvalidCastException ex) { Log.WriteException(ex); valueObj = false; } return valueObj; } 
0
source

All Articles