I want to write function that coder write what date type he want to insert to program, then the function checked whether it possible to convert a certain input to this type. The problem is, that I don't know how to let coder choose date type.
i tried type typeof valuetype etc.
public object checkvalu()//(type t)I added the empty brackets just for the code to run
{
//t output; This is the original code.
int output;//Not found in original code, I just added the code to run
string input = null;
bool b =int.TryParse(input, out output);
while (b != true)
{
Console.WriteLine("the valu is incorct. enter new valu");
input = (Console.ReadLine());
b = int.TryParse(input, out output);
}
output = Convert.ToInt32(input);
return output;
}
public object checkvalu(type t) I do not know what to put in brackets.
I'm assuming few things since they are unclear:
type t
in your code, So here the thing:
public static object CheckValue(string type)
{
// Get the type from string
Type t = Type.GetType(type);
// Used in the loop
bool isConvertable = false;
// Initialize object
object convertInput = null;
Console.Write("Enter a value: ");
while (isConvertable == false)
{
try
{
string input = Console.ReadLine();
convertInput = Convert.ChangeType(input, t);
isConvertable = true;
}
catch (Exception)
{
// If the conversion throw an exception, it means that it has an incorrect type
Console.Write("The value is incorrect, enter new value: ");
}
}
// Just for output purpose
Console.WriteLine("Value has the correct type!");
return convertInput;
}
When you call it like this:
CheckValue("System.Int32");
This will be the output:
Enter a value: this is a string
The value is incorrect, enter new value: 10
Value has the correct type!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.