473,387 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Testing data type

AAJ
Hi

has anyone come across a function to check if a particular string can be
safely converted to a datatype

i.e. i would like to check things like

TypeCheck("1/1/2006",datetime) -returns true

TypeCheck("fred",datetime) -returns false

Typecheck("100"),int32) -returns true

Typecheck("100.121"),int32) -returns false

etc....
I know I could write by own by testing within a try{} block, but I wonder if
anyone already has one already tested and working

Andy
Nov 2 '06 #1
3 5779
Hi Andy,

In the 2.0 framework many Types (including primitives) now have TryParse
methods. I really don't think there is any other way to see if a string value
is of a certain format without attempting to parse it.

In earlier versions of the framework I would perform the parsing on a case by
case basis, but I can see how a simple utility may have come in handy.
Writing a utility for this is trivial, so if you find yourself parsing strings
in many different places in code then you might want to consider writing your
own.

This is the signature commonly used by the 2.0 classes, in case you're
wondering:

public static bool TryParse(string s, out [type] result)

IMO, the sig could be improved for checking whether a string can be parsed
without having to store the result in a variable. But even now it's much
nicer than having to write Try...Catch statements all over the place :)

--
Dave Sexton

"AAJ" <a.a.comwrote in message news:u9**************@TK2MSFTNGP04.phx.gbl...
Hi

has anyone come across a function to check if a particular string can be
safely converted to a datatype

i.e. i would like to check things like

TypeCheck("1/1/2006",datetime) -returns true

TypeCheck("fred",datetime) -returns false

Typecheck("100"),int32) -returns true

Typecheck("100.121"),int32) -returns false

etc....
I know I could write by own by testing within a try{} block, but I wonder if
anyone already has one already tested and working

Andy

Nov 2 '06 #2
Well, on a 1-by-1 basis you can look at the TryParse signature in 2.0 -
however this is static so not that re-usable in a generic sense. For a more
generic approach, TypeConverter may be of use:

using System;
using System.ComponentModel;
class Program
{
static void Main()
{
Console.WriteLine(CanConvert<DateTime>("Fred"));
Console.WriteLine(CanConvert<DateTime>("1/1/2006"));
Console.WriteLine(CanConvert<int>("100"));
Console.WriteLine(CanConvert<int>("100.134"));

}
// 2.0 variant
private static bool CanConvert<TTo>(object valueFrom)
{
return CanConvert(typeof(TTo), valueFrom);
}
// 1.1 friendly
private static bool CanConvert(Type typeTo, object valueFrom)
{
// TODO: check for null params first...
TypeConverter converter = TypeDescriptor.GetConverter(typeTo);
Type typeFrom = valueFrom.GetType();
if (converter == null || !converter.CanConvertFrom(typeFrom) ||
!converter.IsValid(valueFrom))
{
return false;
}
try {
converter.ConvertFrom(valueFrom); // test the conversion
return true;
} catch {
return false; // damnit!
}
}
}
Nov 2 '06 #3
AAJ
Thanks guys

I'm running 2.0 and I shall give the suggestions a try

cheers again
Andy
"AAJ" <a.a.comwrote in message
news:u9**************@TK2MSFTNGP04.phx.gbl...
Hi

has anyone come across a function to check if a particular string can be
safely converted to a datatype

i.e. i would like to check things like

TypeCheck("1/1/2006",datetime) -returns true

TypeCheck("fred",datetime) -returns false

Typecheck("100"),int32) -returns true

Typecheck("100.121"),int32) -returns false

etc....
I know I could write by own by testing within a try{} block, but I wonder
if anyone already has one already tested and working

Andy

Nov 3 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Hugh Cowan | last post by:
Hello, I don't program full-time (anymore), but I do try and stay on-top of the latest technologies and like most are always trying to upgrade my skills and remain current (as much as is...
4
by: Nathon Dalton | last post by:
I need to know what the appropriate way to test for nothing in several different types of data types is. Here are some examples For string I use this If Not abc.text Is Nothing AndAlso Not...
72
by: Jacob | last post by:
I have compiled a set og unit testing recommendations based on my own experience on the concept. Feedback and suggestions for improvements are appreciated: ...
10
by: Sean Chambers | last post by:
Hello, I am attempting to utilize the MVP pattern in a new app I am building. I am using TDD, along with mock views attached to the View interface to attempt to unit test the UI. The problem I...
6
by: Dick | last post by:
I’d appreciate some advice regarding unit tests. My questions are general in nature but (as usual) best conveyed via a (simplified) example: I have a table that contains two columns – the...
1
by: iLL | last post by:
If I have a collection of polymorphic objects, is there a way to test exactly what data type an element of that collection is? I’ve though of two workarounds: 1. Type casting and testing...
2
by: Luc The Perverse | last post by:
Hello! I am trying to find a way to deal with Windows' case insensitivity without just forcing everything lowercase. While I am open to criticism on my method - my question relates to the...
0
by: Matthew Fitzgibbons | last post by:
I'm by no means a testing expert, but I'll take a crack at it. Casey McGinty wrote: I've never run into this. Rule of thumb: always separate software from hardware. Write mock classes or...
4
by: Emanuele D'Arrigo | last post by:
Hi everybody, I'm just having a go with Unit Testing for the first time and my feeling about it in short is: Neat! I'm a bit worried about the time it's taking me to develop the tests but...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.