title: Can I check if a variable can be cast to a specified type?
body: <p>I am trying to verify whether a variable that is passed can be converted to a specific type.  I have tried the following but can't get it to compile so I assume I'm going about it the wrong way (I'm new to C#)</p>
  
  <pre><code>string myType = "System.Int32";
  string myValue = "42";
  
  bool canBeCast = false;
  
  try
  {
    // try to convert the value to it's intended type to see if it's valid.
    var result = (Type.GetType(typeString))dataValue;
    canBeCast = true;
  }
  catch
  {
    canBeCast = false;
  }
  </code></pre>
  
  <p>I'm basically trying to avoid a massive switch statement along the lines of</p>
  
  <pre><code>  switch(myType){
      case "System.Int32":
        try
        {
          var convertedValue = Convert.ToInt32(myValue);
        }
        catch (Exception)
        {
          canBeConverted = false;
        }
        break;
      case "another type":
        ...
    }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>Ok, basically I have a db table of known input types that looks like:</p>
  
  <pre><code>CREATE TABLE [dbo].[MetadataTypes] (
      [typeName]  VARCHAR (50)  NOT NULL,
      [dataType]  VARCHAR (50)  NOT NULL,
      [typeRegex] VARCHAR (255) NULL
  );
  </code></pre>
  
  <p>which may have data such as </p>
  
  <pre><code>"StartTime","System.DateTime",null
  "TicketId","System.String","$[Ff][0-9]{7}^"
  </code></pre>
  
  <p>And the input to my function would be a KeyValuePair along the lines of </p>
  
  <pre><code>myInput = new KeyValuePair&lt;string,string&gt;("StartTime","31/12/2010 12:00");
  </code></pre>
  
  <p>I need to check that the value of the KeyValuePair is of the correct datatype expected by the MetaDataType.</p>
  
  <p>EDIT FOR ANSWER:</p>
  
  <p>Leon got really close to the solution I finally came up with.</p>
  
  <p>For reference my function now looks like this:</p>
  
  <pre><code>public Boolean ValidateMetadata(KeyValuePair&lt;string, string&gt; dataItem)
  {
  
    // Look for known metadata with name match
    MetadataType type = _repository.GetMetadataTypes().SingleOrDefault(t =&gt; t.typeName == dataItem.Key);
    if (type == null) { return false; }
  
    // Get the data type and try to match to the passed in data item.
    Boolean isCorrectType = false;
    string typeString = type.dataType;
    string dataValue = dataItem.Value;
  
    try
    {
      var cValue = Convert.ChangeType(dataValue, Type.GetType(typeString));
      isCorrectType = true;
    }
    catch
    {
      isCorrectType = false;
    }
  
    //TODO: Validate against possible regex here....            
  
    return isCorrectType;
  
  }
  </code></pre>