473,545 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to parse various types without a switch?

Hi,
I need to read a big CSV file, where different fields should be converted to
different types,
such as int, double, datetime, SqlMoney, etc.

I have an array, which describes the fields and their types. I would like
to somehow store a reference to parsing operations in this array
(such as Int32.Parse, Double.Parse, SqlMoney.Parse, etc),
so I can invoke the appropriate one without writing a long switch.

Using reflection is not an option for performance reasons.

I tried to create a delegate, but since Int32.Parse, Double.Parse, etc.
all have different return types, creating a common delegate type
appears to be impossible.

For now I ended up writing wrappers around Parse methods for each type,
such as
static object ParseDouble(str ing str) {return double.Parse(st r);}
then inserting delegates to these methods into the array.

This seems to work, but it looks pretty ugly. I still hope that .NET
framework
has a way to do it in official way, which I overlooked. For example,
it has interface IConvertible, which can be used to achieve opposite:
convert
an object to various types, but I cannot find an official way to do parsing.

Thank you
John

Aug 7 '05 #1
24 3136
John,

You have crossposted (nothing wrong with) however I think that you be better
of with crossposting this to a language newsgroup too, because we don't know
what program language you are using now.

The two largest developer newsgroups of Microsoft are beside Excel.developer
and ASPNET

microsoft.publi c.dotnet.csharp
and
microsoft.publi c.dotnet.langua ges.vb

At least when you post to the two newsgroups that you are posting now, tell
us than what program language you use.

I hope this helps,

Cor
Aug 7 '05 #2
hB
since Parse() is not declared in interface, you have to create
wrappers.
It would be like object Parse(string csvstrword);

(In C we have sscanf, it can read into many datatypes.)
---
hB

Aug 7 '05 #3

<John> wrote in message news:rf******** ************@sp eakeasy.net...
Using reflection is not an option for performance reasons.
Reflection doesn't have to be slow. You can't get rid of the overhead, but
if you code it correctly it can be quite fast.
I tried to create a delegate, but since Int32.Parse, Double.Parse, etc.
all have different return types, creating a common delegate type
appears to be impossible.


Return an object and unbox it (if applicable) after the delegate returns.
This will have less overhead than reflection.

Or, if you can resolve the actual type of the value being parsed you can
create a sort of generic converter function using Convert.ChangeT ype:

public object TryParse(object /* string */ val, System.Type type) {
try {
return Convert.ChangeT ype(val, type);
}
catch {
return null;
}
}

And call it like:

string s = "3.41";
double d = (double) TryParse(s, System.Double);
--
Klaus H. Probst, MVP
http://www.simulplex.net/
Aug 7 '05 #4
hB
I have a better solution, if I understand your problem correctly :P

Assumption.
since CSV has data, all in strings, like
1, "name" , "rank", "1.2.2006"
.....

Example:
[STAThread]
static void Main(string[] args)
{
IFF[] i = new IFF[2];
i[0] = new BFF(new Int32());
i[1] = new BFF(new Double());

object o = i[0].parse("1");//You have CSV in a proper manner
o = i[1].parse("1.1");
}

public interface IFF
{
object parse(string s);
}

public class BFF : IFF
{
private object myobj;
public BFF(object ob)
{
myobj = ob;
}

public object parse(string s)
{
try
{
Type tp = myobj.GetType() ;
System.Reflecti on.MethodInfo mi = tp.GetMethod("P arse",new
Type[]{typeof(System. String)});
object[] param = new object[1];
param[0] = s ;
object o = mi.Invoke(myobj ,param);
//myobj.Parse(o);
return o;
}
catch
{
return null;
}
}
}

Aug 7 '05 #5
John,

I thought that Paul was more active in some other newsgroups the last time.

However I see he is it here as well.

See what he wrote about your problem in this newsgroup.
http://groups-beta.google.com/group/...ae67bf4?hl=en&

I am not so familiar with those Ini files so maybe you can search for that
when the message from Paul is not sufficient enough or wait until he sees
this. Your subject is however not one that in my opinion gets direct the eye
from Paul.

I hope this helps,

Cor
Aug 7 '05 #6
hB
I think i have provided John a pretty easy way.
Note that reflection can be used only once, just extract methodinfo and
then keep invoking it in parse() function.

---
hB

Aug 7 '05 #7
Thank you for the answer.
You have crossposted
It is very hard to figure out the difference between
microsoft.publi c.dotnet.framew ork and microsoft.publi c.dotnet.genera l
What is the proper place to post questions about the library?
I think that you be better of with crossposting this to a language
newsgroup too, because we don't know what program language you are using
now.
At least when you post to the two newsgroups that you are posting now,
tell us than what program language you use.


I don't understand, what's the difference? My question is about the library
(Framework),
not the language. I guess all (or most) of the solutions, such as
interfaces, delegates, reflection, etc. are available to both C# and VB.
Currently I write on C#, but this should not matter.

Thank you
John
Aug 7 '05 #8
Thank you for the answer.
since Parse() is not declared in interface, you have to create wrappers.


Yes, this is what I ended up doing (see my original post):

static object ParseDouble(str ing str) {return double.Parse(st r);}
.....

I just wanted to double check whether I am missing some standard solution,
and, actually, I was missing Convert.ChangeT ype, as Klaus H. Probst showed.

John
Aug 7 '05 #9
Thank you for answer.
Reflection doesn't have to be slow. You can't get rid of the overhead, but
if you code it correctly it can be quite fast.
May be it does not have to be, but it is.

Unfortunately, in my own benchmarking calling a static empty method
without arguments using reflection (MethodInfo.Inv oke) is 300 times
slower than a direct call,
calling the same method using a delegate is 10% slower.
Calling Int32.Parse using reflection is 15 times slower than a direct call,
delegate is 0.5% slower.
So, I will not use reflection is a loop (unless you show that my results are
wrong).

can create a sort of generic converter function
Convert.ChangeT ype(val, type);


Thank you, I completely missed this one in my original search.
However, I am not going to use it.
Convert.ChangeT ype is implemented as a kind of a switch,
which I tried to avoid at the first place. As the result:
- it is 30% slower than the delegate
- it can only handle standard types and not the Sql* types.

Thank you
John
Aug 7 '05 #10

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

Similar topics

7
1523
by: selekta | last post by:
hi, i've recently started to deal a little bit with tcp/ip-socket-programming (linux). Now i've written a little test-program (as displayed further down). When i'm trying to compile it the gcc-compiler return "parse error in l.23/.24 before token '='. " the line before those two ( host_addr.sin_family = AF_INET;) is acepted without any...
19
3205
by: Johnny Google | last post by:
Here is an example of the type of data from a file I will have: Apple,4322,3435,4653,6543,4652 Banana,6934,5423,6753,6531 Carrot,3454,4534,3434,1111,9120,5453 Cheese,4411,5522,6622,6641 The first position is the info (the product) I want to retreive for the corresponding code. Assuming that the codes are unique for each product and all...
24
396
by: | last post by:
Hi, I need to read a big CSV file, where different fields should be converted to different types, such as int, double, datetime, SqlMoney, etc. I have an array, which describes the fields and their types. I would like to somehow store a reference to parsing operations in this array (such as Int32.Parse, Double.Parse, SqlMoney.Parse, etc),...
0
7484
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7928
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7440
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5997
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4963
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3451
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1902
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1030
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
726
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.