From C to C#

G

Guest

I've been writing C for 20+ years and am finally making the transition to C#.
I understand generally how struct and enum have changed. The data I want to
represent can be thought of as "rows" so in C I'd use an array of structs -
not an option in C#. I'd like to combine an enum to make the code more
readable. My data looks something like:

string strShortName
int intIndex
string strLongName

The values for strIndex are not sequential. I'd like to be able to build a
single "structure" that contains all of the data. In C I'd have done
something like:

enum { Small = 2, Medium = 5, Large = 15 };

struct myStruct {
char *strShortName;
int intIndex;
char *strLongName;
}

Then I'd have used something like:

struct myStruct mydata[] = {
{ "Small", Small, "Something Small" },
{ "Medium", Medium, "Something Medium" },
{ "Large", Large, "Something Large" },
....
{ NULL, 0, NULL }
};

I'd have finished with a couple of functions to return my values for
intIndex or strLongName when passed a strShortName. Of course, they'd have to
iterate through the array but it's not a problem since it's relatively small.
I know that achieving this functionality in an elegant way in C# must be
possible but lacking a language "reference" (no, the "Teach Yourself" books
don't get it for language details) I'm a bit frustrated.

Thanks!
 
M

Marc Gravell

Well, 2-out-of-3 are there immedately via enum; for the last...
perhaps attributes against the individual enums? How about:

public enum FooSize {
[Description("Small somet")]
Small = 2,
[Description("Medium thingy")]
Medium = 5,
[Description("Large wossit")]
Large = 15
}

public static class EnumHelper {
public static T ParseName<T>(string name) where T : struct {
return (T)Enum.Parse(typeof(T), name);
}
public static T ParseName<T>(string name, bool ignoreCase)
where T : struct {
return (T)Enum.Parse(typeof(T), name, ignoreCase);
}
public static string GetName<T>(T value) {
return value.ToString(); // trivial
}
public static string GetDescription<T>(T value) where T :
struct {
foreach (FieldInfo fi in
typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public)) {
if (fi.FieldType == typeof(T) &&
(value.Equals((T)fi.GetValue(null)))) {
foreach (DescriptionAttribute attrib in
fi.GetCustomAttributes(typeof(DescriptionAttribute), false)) {
return attrib.Description;
}
return fi.Name; // default to name if no
description
}
}
throw new InvalidOperationException(string.Format("Value
{0} not found for {1}", value, typeof(T).Name));
}
}

static void Main() {
FooSize size = FooSize.Medium;
string name = EnumHelper.GetName(size);
FooSize parsed = EnumHelper.ParseName<FooSize>(name);
string desc = EnumHelper.GetDescription(parsed);
}
 
A

Ashot Geodakov

public enum EIndex
{
Small = 2,
Mediun = 5,
Large = 15
}

public struct MyStruct
{
public string strShortName;
public EIndex intIndex;
public string strLongName;

public MyStruct( string strShort, EIndex intI, string strLong )
{
strShortName = strShort;
intIndex = intI;
strLongName = strLong;
}
}

MyStruct[] myData = new MyStruct[]
{
new MyStruct( "Small", EIndex.Small, "Something Small" ),
new MyStruct( "Medium", EIndex.Medium, "Something Medium" ),
new MyStruct( "Large", EIndex.Large, "Something Large" )
}

for( int i = 0; i < myData.Length; i ++ )
{
if( myData.intIndex == EIndex.Small )
{
}
}

foreach( MyStruct myS in myData )
{
if( myS.strShortName.CompareTo( "Small" ) == 0 )
{
}
}


///// Now don't forget to "free" all your memory that is used by myData
array! :):):)
 
M

Marc Gravell

Forgot to say - you can simply cast to get the int value:

FooSize size = FooSize.Medium;
int sizeValue = (int) size;

Marc
 
C

Chris Nahr

I've been writing C for 20+ years and am finally making the transition to C#.
I understand generally how struct and enum have changed. The data I want to
represent can be thought of as "rows" so in C I'd use an array of structs -
not an option in C#. I'd like to combine an enum to make the code more
readable.

Why do you think an array of structs is not an option in C#? Your
myStruct is a small data container, and if you don't need/want
reference semantics a C# struct would do just fine.

Here's a straightforward translation of your code to C#:

public enum DataSize
{
Small = 2,
Medium = 5,
Large = 15
}

public struct MyStruct
{
string ShortName;
DataSize Index;
string LongName;

public MyStruct(string shortName,
DataSize index, string longName)
{
ShortName = shortName;
Index = index;
LongName = longName;
}
}

public class NameOfYourClassSinceEverythingMustBeInAClass
{
public MyStruct[] MyData = new MyStruct[]
{
new MyStruct("Small", DataSize.Small, "Something Small" ),
new MyStruct("Medium", DataSize.Medium, "Something Medium"),
new MyStruct("Large", DataSize.Large, "Something Large")
};
}

You don't need an end-of-array marker with null data since .NET arrays
store their size internally.
I'd have finished with a couple of functions to return my values for
intIndex or strLongName when passed a strShortName. Of course, they'd have to
iterate through the array but it's not a problem since it's relatively small.

I know that achieving this functionality in an elegant way in C# must be
possible but lacking a language "reference" (no, the "Teach Yourself" books
don't get it for language details) I'm a bit frustrated.

If you have Visual Studio 2005 installed you will find the C# language
reference in this subdirectory: VC#\Specifications\1033

The same text is available as a printed book: "The C# Programming
Language" (2nd ed.) by Anders Heijlsberg, the language's architect.

That's very dry reading, though, and I'd prefer something like "A
Programmer's Introduction to C# 2.0" (3rd ed.) by Gunnerson/Wienholt
to get an idea of the C# language.
 
M

Michael A. Covington

One thought: I think the transition from C to C# is easier if you
understand that they are fundamentally unrelated languages that happen to
have a similar syntax on the surface.

In particular, in C a lot of pointer handling is up to you, while in C#, the
pointer handling is done automatically by the runtime system. Ditto for
memory management.
 
A

Andy

One thought: I think the transition from C to C# is easier if you
understand that they are fundamentally unrelated languages that happen to
have a similar syntax on the surface.

In particular, in C a lot of pointer handling is up to you, while in C#, the
pointer handling is done automatically by the runtime system. Ditto for
memory management.

Also keep in mind that C is a functional programming paradigm, while
C# is an object oriented one. That's a huge difference.
 
P

Peter Duniho

Also keep in mind that C is a functional programming paradigm, while
C# is an object oriented one. That's a huge difference.

Hmmm...I'd disagree with that statement. "Functional programming" is very
different from what C or C# offer (which are procedural). See, for
example: http://en.wikipedia.org/wiki/Functional_programming

That said, I'd also disagree with the statement that C and C# are
"fundamentally unrelated". They are clearly related, and I'd say that
about 75% of C# is basically the same as C, maybe more. C# even has the
same pointer syntax, though you usually don't use it.

Pete
 
G

Guest

I've studied your example and understand most of it. To get it to compile,
and after consulting the section on Attributes in the C# Language
Specification, I added the following at the top:

public class DescriptionAttribute: Attribute
{
public string Description;
public DescriptionAttribute( string value )
{
Description = value;
}
public string Value
{
get { return ( Description ); }
set { Description = Value; }
}
}

Thanks for the help!
 
G

Guest

Thanks - That's exactly what I was trying to do after a day of experimenting.
The syntax:

MyStruct[] myData = new MyStruct[]

is part of what was tripping me up. I'd naturally want to write (in C style)
something like:

MyStruct myData[] = new MyStruct[]



Ashot Geodakov said:
public enum EIndex
{
Small = 2,
Mediun = 5,
Large = 15
}

public struct MyStruct
{
public string strShortName;
public EIndex intIndex;
public string strLongName;

public MyStruct( string strShort, EIndex intI, string strLong )
{
strShortName = strShort;
intIndex = intI;
strLongName = strLong;
}
}

MyStruct[] myData = new MyStruct[]
{
new MyStruct( "Small", EIndex.Small, "Something Small" ),
new MyStruct( "Medium", EIndex.Medium, "Something Medium" ),
new MyStruct( "Large", EIndex.Large, "Something Large" )
}

for( int i = 0; i < myData.Length; i ++ )
{
if( myData.intIndex == EIndex.Small )
{
}
}

foreach( MyStruct myS in myData )
{
if( myS.strShortName.CompareTo( "Small" ) == 0 )
{
}
}


///// Now don't forget to "free" all your memory that is used by myData
array! :):):)


BillP3rd said:
I've been writing C for 20+ years and am finally making the transition to
C#.
I understand generally how struct and enum have changed. The data I want
to
represent can be thought of as "rows" so in C I'd use an array of
structs -
not an option in C#. I'd like to combine an enum to make the code more
readable. My data looks something like:

string strShortName
int intIndex
string strLongName

The values for strIndex are not sequential. I'd like to be able to build a
single "structure" that contains all of the data. In C I'd have done
something like:

enum { Small = 2, Medium = 5, Large = 15 };

struct myStruct {
char *strShortName;
int intIndex;
char *strLongName;
}

Then I'd have used something like:

struct myStruct mydata[] = {
{ "Small", Small, "Something Small" },
{ "Medium", Medium, "Something Medium" },
{ "Large", Large, "Something Large" },
...
{ NULL, 0, NULL }
};

I'd have finished with a couple of functions to return my values for
intIndex or strLongName when passed a strShortName. Of course, they'd have
to
iterate through the array but it's not a problem since it's relatively
small.
I know that achieving this functionality in an elegant way in C# must be
possible but lacking a language "reference" (no, the "Teach Yourself"
books
don't get it for language details) I'm a bit frustrated.

Thanks!
 
M

Marc Gravell

Ahh... sorry, I didn't clarify... DescriptionAttribute is already
defined (in System.ComponentModel, so "using System.ComponentModel;"
would have done the job), and is used by a range of things, e.g.
PropertyDescriptors. Your own attribute will work just as well (since
the regular Enum implementation doesn't do anything specific with this
attribute in this context).

But: you got the implementation pretty much right, so kudos. At a push
I'd expose the Description as a property instead of a field, and
perhaps make it readonly and mark the class as immutable.

Marc
 
G

Guest

Not at all... As a C and assembly programmer I tend to be something of a
control freak where my code is concerned. (I actually prefer writing
assembly!) As such I want to understand exactly what every line of code does.
Your solution was a great learning exercise. I appreciate that you took the
time to respond.
 
J

Jon Skeet [C# MVP]

Not at all... As a C and assembly programmer I tend to be something of a
control freak where my code is concerned. (I actually prefer writing
assembly!) As such I want to understand exactly what every line of code does.

In that case I'd recommend learning the difference between structs and
classes ASAP. (Heck, I'd recommend that to anyone anyway.)

You may already know it, of course, but it's basically not as it is in
C++, nor is a struct quite what it was in C. Classes are much more
widely used than structs in C# - it's very rare to define your own
struct.

See http://pobox.com/~skeet/csharp/references.html
for a bit of an intro to the topic, along with
http://pobox.com/~skeet/csharp/memory.html and http://pobox.com/~skeet/csharp/parameters.html

(Obviously there will be plenty of other pages on the web - I just
happen to know those URLs without looking any further :)

Jon
 
J

Jon Skeet [C# MVP]

That said, I'd also disagree with the statement that C and C# are
"fundamentally unrelated". They are clearly related, and I'd say that
about 75% of C# is basically the same as C, maybe more. C# even has the
same pointer syntax, though you usually don't use it.

There are various programming language "family trees" around - it
might be interesting some time to split them into two; "syntactic
relations" and "paradigm relations". For instance, VB6 and VB.NET are
syntactically related but relatively weakly paradigm-related, whereas
VB.NET and C# are strongly paradigm-related but weakly syntactically
related.

Admittedly I'm not sure I'd use the word paradigm here if I were doing
it properly, but it's the best I could come up with in the course of
writing this post :)

Jon
 
G

Guest

Peter said:
Hmmm...I'd disagree with that statement. "Functional programming" is
very different from what C or C# offer (which are procedural). See, for
example: http://en.wikipedia.org/wiki/Functional_programming

You are obvious right.

I suspect Any has been tricked by the fact that a procedure in C
is called a (void) function.
That said, I'd also disagree with the statement that C and C# are
"fundamentally unrelated". They are clearly related, and I'd say that
about 75% of C# is basically the same as C, maybe more. C# even has the
same pointer syntax, though you usually don't use it.

Maybe 75% same syntax.

I think it would very rare to see a C program and a C# program solving
the same problem having the same structure.

Arne
 
P

Peter Duniho

Maybe 75% same syntax.

I think it would very rare to see a C program and a C# program solving
the same problem having the same structure.

I guess it depends on your definition of "structure", and whether you
include C++ as a close relative of C.

Fact is, I don't see a lot different in my code in C# versus how I used to
do things. The biggest difference is that I have easy access to a very
nice library that handles a wide variety of things for me. I could write
all the same code I'm doing in C#, using managed C++, and it would work
fine (though I'd have to do a lot more typing, because of all the extra ^
characters manage C++ has :) ).

There are certainly some crucial differences between managed code and
unmanaged code, but as far as I'm concerned, they mostly wind up just
being icing on the cake. For example, unlike some programmers I've met, I
never had trouble managing my allocated data, leaking memory, etc. Yes,
it's much nicer to not have to remember to explicitly free references, and
the code winds up looking a lot nicer as a result. But it's not *that*
much of an inconvenience to have to do that management explicitly.

For that matter, before I coded in C++, I used a lot of OOP-like
techniques in C. There's very little you can do in C++ that you can't do
in C, just with more typing. The key characteristics of OOP in particular
are not hard to design into a C program.

In fact, if it weren't for significant differences like the memory
management model, immutable types, broader differences between structs and
classes, etc. in .NET/C#, I would've ranked C# even closer to C/C++ than
75%. Fact is, I didn't undergo any sort of radical philosophical or
paradigmatic shift when I started doing C# programming. "I could quit C#
any time I wanted to" :) and just go back to native Windows programming in
C or C++.

I realize it's a subjective sort of question (it's not like I have a
scientifically valid way of measuring that 75% I'm talking about), but it
seems to me that my transition to C# should have been a lot harder if the
language and environment were really that big of a change from what I was
already used to. And I can't say that other than having this huge library
to draw from, I feel like .NET/C# has dramatically changed the way I think
about my programs, which to me is the key factor when a language is
genuinely a radical departure from some other language.

I find C# to be a natural progression from C, C++, Pascal, and even VB to
some extent. Even an archaic language like FORTRAN has genetic markers in
C#. :) Contrast that to languages like FORTH, Lisp, Prolog, etc. which
are *really* different from procedural languages.

Anyway, I don't disagree with Jon's attempt to look at language
similarities from two different points of view, but even if you look at
what he's calling the "paradigm relation", I just don't see that big a
chasm between C# and the previous iterations of "C" languages.

Pete
 
P

Peter Duniho

[...]
I find C# to be a natural progression from C, C++, Pascal, and even VB
to some extent. Even an archaic language like FORTRAN has genetic
markers in C#. :) Contrast that to languages like FORTH, Lisp, Prolog,
etc. which are *really* different from procedural languages.

And yes, just to clarify, I do realize FORTH is procedural. But it's a
procedural language that really does have some dramatic differences in the
basic structure of the language from the others I mentioned.
 
M

Michael A. Covington

For that matter, before I coded in C++, I used a lot of OOP-like
techniques in C. There's very little you can do in C++ that you can't do
in C, just with more typing. The key characteristics of OOP in particular
are not hard to design into a C program.

In fact, if it weren't for significant differences like the memory
management model, immutable types, broader differences between structs and
classes, etc. in .NET/C#, I would've ranked C# even closer to C/C++ than
75%. Fact is, I didn't undergo any sort of radical philosophical or
paradigmatic shift when I started doing C# programming. "I could quit C#
any time I wanted to" :) and just go back to native Windows programming in
C or C++.

That's because you're a disciplined programmer. You have definite
techniques in mind, and you use your language to implement them. (That's a
good thing.) I've been there -- for example, I used Fortran and PL/1 in a
Pascal-like way before Pascal came along. And my C++ is a lot more orderly
than the language invites it to be.

Many programmers work the other way -- they take the language and put its
parts together any old way. That's where C# imposes a paradigm shift.
Klutzing around in C# is very different from klutzing around in C.
 
G

Guest

Peter said:
I guess it depends on your definition of "structure", and whether you
include C++ as a close relative of C.

A C++ solution will definitely have more in common with a C# solution
than a C solution. Things like OO etc.
Fact is, I don't see a lot different in my code in C# versus how I used
to do things. The biggest difference is that I have easy access to a
very nice library that handles a wide variety of things for me. I could
write all the same code I'm doing in C#, using managed C++, and it would
work fine (though I'd have to do a lot more typing, because of all the
extra ^ characters manage C++ has :) ).

Managed C++ and C# solution would obvious be almost identical in
most cases.
For example, unlike some programmers I've met,
I never had trouble managing my allocated data, leaking memory, etc.
Yes, it's much nicer to not have to remember to explicitly free
references, and the code winds up looking a lot nicer as a result. But
it's not *that* much of an inconvenience to have to do that management
explicitly.

Except that experience shows that on a sufficient large project there
are always some that does not get it right.
For that matter, before I coded in C++, I used a lot of OOP-like
techniques in C. There's very little you can do in C++ that you can't
do in C, just with more typing.

Since the first C++ compiler (cfront) actually translated C++ to
C then that is obvious true.

But the whole purpose of a language is to make it easy. Else we
could just as well code in assembler.
In fact, if it weren't for significant differences like the memory
management model, immutable types, broader differences between structs
and classes, etc. in .NET/C#, I would've ranked C# even closer to C/C++
than 75%. Fact is, I didn't undergo any sort of radical philosophical
or paradigmatic shift when I started doing C# programming. "I could
quit C# any time I wanted to" :) and just go back to native Windows
programming in C or C++.

I realize it's a subjective sort of question (it's not like I have a
scientifically valid way of measuring that 75% I'm talking about), but
it seems to me that my transition to C# should have been a lot harder if
the language and environment were really that big of a change from what
I was already used to. And I can't say that other than having this huge
library to draw from, I feel like .NET/C# has dramatically changed the
way I think about my programs, which to me is the key factor when a
language is genuinely a radical departure from some other language.

Either your C coding style is unusual or your C# ditto is.
Anyway, I don't disagree with Jon's attempt to look at language
similarities from two different points of view, but even if you look at
what he's calling the "paradigm relation", I just don't see that big a
chasm between C# and the previous iterations of "C" languages.

Well - I would say only 10% similarity between C and C# for
code structure or style or whatever we call what is not syntax.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top