473,804 Members | 3,251 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic way of writing this enum code?

Hi
The methods below are identical except they take as arguments
different enum types.
There must be a better way of writing this?

ta
public string ConcatValues(pa rams EnumType1 [] types)
{
StringBuilder sb = new StringBuilder() ;
bool first = true;
foreach (EnumType1 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int) type);
}

return sb.ToString();
}

public string ConcatValues(pa rams EnumType2 [] types)
{
StringBuilder sb = new StringBuilder() ;
bool first = true;
foreach (EnumType2 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int) type);
}

return sb.ToString();
}

etc

Oct 29 '07 #1
4 1847
You can use generics to do this:

public string ConcatValues<T> (params T[] types)
{
// Check to make sure that T is an enumeration.
if (!typeof(T).IsE num)
{
// Throw an exception.
throw new InvalidOperatio nException("The type parameter T must be an
enumeration type.");
}

// Create the string builder.
StringBuilder sb = new StringBuilder() ;

foreach (T type in types)
{
// Append.
sb.Append((int) type);
sb.Append(",");
}

// Remove the comma, if necessary.
if (sb.Length 0)
{
// Remove the comma.
sb.Remove(sb.Le ngth - 1, 1);
}

// Return the string.
return sb.ToString();
}

Note that you have to check to make sure that the type T is an
enumeration at runtime, since the compiler will not allow you to create a
constraint against System.Enum (which all enumerations derive from).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
<co**********@g ooglemail.comwr ote in message
news:11******** **************@ 22g2000hsm.goog legroups.com...
Hi
The methods below are identical except they take as arguments
different enum types.
There must be a better way of writing this?

ta
public string ConcatValues(pa rams EnumType1 [] types)
{
StringBuilder sb = new StringBuilder() ;
bool first = true;
foreach (EnumType1 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int) type);
}

return sb.ToString();
}

public string ConcatValues(pa rams EnumType2 [] types)
{
StringBuilder sb = new StringBuilder() ;
bool first = true;
foreach (EnumType2 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int) type);
}

return sb.ToString();
}

etc

Oct 29 '07 #2
Hey,

Just add a GenericType and change your EnumTypes1[] to the generic type and
access them that way -

<code>
public string ConcatValues<Ge nericType>(para ms GenericType[] types)
{

}
</code>

You might also be interested in:
Generic Parameters :
http://msdn2.microsoft.com/en-us/lib...x2(VS.80).aspx
Generics : http://msdn2.microsoft.com/en-us/lib...7t(VS.80).aspx

HTH
Brendon

<co**********@g ooglemail.comwr ote in message
news:11******** **************@ 22g2000hsm.goog legroups.com...
Hi
The methods below are identical except they take as arguments
different enum types.
There must be a better way of writing this?

ta
public string ConcatValues(pa rams EnumType1 [] types)
{
StringBuilder sb = new StringBuilder() ;
bool first = true;
foreach (EnumType1 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int) type);
}

return sb.ToString();
}

public string ConcatValues(pa rams EnumType2 [] types)
{
StringBuilder sb = new StringBuilder() ;
bool first = true;
foreach (EnumType2 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int) type);
}

return sb.ToString();
}

etc
Oct 29 '07 #3

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in
message news:ek******** ******@TK2MSFTN GP04.phx.gbl...
You can use generics to do this:

public string ConcatValues<T> (params T[] types)
{
// Check to make sure that T is an enumeration.
if (!typeof(T).IsE num)
{
// Throw an exception.
throw new InvalidOperatio nException("The type parameter T must be
an enumeration type.");
}

// Create the string builder.
StringBuilder sb = new StringBuilder() ;

foreach (T type in types)
{
// Append.
sb.Append((int) type);
This line won't compile, because there's no constraint making T convertible
to an integer. Add a constraint "where T : IConvertible" and use
"type.ToInt32(n ull)".
sb.Append(",");
}

// Remove the comma, if necessary.
if (sb.Length 0)
{
// Remove the comma.
sb.Remove(sb.Le ngth - 1, 1);
}

// Return the string.
return sb.ToString();
}

Note that you have to check to make sure that the type T is an
enumeration at runtime, since the compiler will not allow you to create a
constraint against System.Enum (which all enumerations derive from).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
<co**********@g ooglemail.comwr ote in message
news:11******** **************@ 22g2000hsm.goog legroups.com...
>Hi
The methods below are identical except they take as arguments
different enum types.
There must be a better way of writing this?

ta
public string ConcatValues(pa rams EnumType1 [] types)
{
StringBuilde r sb = new StringBuilder() ;
bool first = true;
foreach (EnumType1 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",") ;
}
sb.Append((int )type);
}

return sb.ToString();
}

public string ConcatValues(pa rams EnumType2 [] types)
{
StringBuilde r sb = new StringBuilder() ;
bool first = true;
foreach (EnumType2 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",") ;
}
sb.Append((int )type);
}

return sb.ToString();
}

etc


Oct 29 '07 #4
Yep, thanks for all the replies. I've put the code in and its working
happily

Oct 31 '07 #5

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

Similar topics

3
3336
by: Claire | last post by:
I have a large record with many enumerated fields. The record is stored in a file and the fields have to be extracted. I validate the data as it's read, but there's so many tests similar to the following that I wondered if it's possible to create a single generic function to perform the validation. Just to keep code size down if nothing else. I'm not that experienced with .net yet so I don't know what's possible. example code reader is...
6
5190
by: Charles Law | last post by:
I want to do something like this: obj = CType(value, Value.Type) Well, not exactly, but I think that captures the essence. I realise it won't work as I have written it, and it looks a bit like a nebulous statement, but I am looking for a generic way to convert a variable of unknown type to its actual type. Perhaps a better example would be
0
1388
by: Zoran Stipanicev | last post by:
Hi! The question is product of laziness. I want to write generic operators for matrix computation which would adapt to different types of matrices i.e. when adding square matrix and lower triangle matrix it would add only elements on and under main diagonal and copy the rest from square matrix. Basically it would allow adding new matrix type (shape) without writing new operators (I'm to lazy
2
2102
by: Stipanicev | last post by:
I want to write generic operators for matrix computation which would adapt to different types (shapes) of matrices i.e. when adding square matrix and lower triangle matrix it would add only elements on and under main diagonal and copy the rest from square matrix. Basically it would allow adding new matrix type (shape) without writing new operators. Here is the code I hope could do that:
3
1757
by: Frederick Gotham | last post by:
For objects, we have "void*" as the generic pointer type. For instance: enum ParamType { Int, Double }; void Func(void *const p,ParamType const pt) { switch (pt) { case Int: *(int*)p = 42; break; case Double: *(double*)p = 42; break;
1
1701
by: shapper | last post by:
Hello, I have an Enum and a Generic.List(Of Enum) 1 Public Enum Mode 2 Count 3 Day 4 Month 5 End Enum
2
12336
by: shapper | last post by:
Hello, I have an Enum and a Generic.List(Of Enum) 1 Public Enum Mode 2 Count 3 Day 4 Month 5 End Enum
2
3522
by: JB | last post by:
Hi All, I'm pulling my hair over this and could really do with a bit of help. I'm using various different enums as bit fields and I'd like to create a set of generic Functions or Subs to manipulate the bitfields. For instance: <Flags()_ Enum ActionFlags As Byte
1
2013
by: dgraper | last post by:
Friends: I'm an ex-VB programmer with a new job in an all C# shop. No problems the past few months thinking/converting between the two, but I just ran into a problem translating some working VB code from C#: Dim enClr As System.Drawing.KnownColor Dim clrs As New System.Collections.Generic.List (Of System.Drawing.KnownColor) clrs.AddRange(System.Enum.GetValues (enClr.GetType()))
0
9708
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10588
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9161
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7623
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4302
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
3
2998
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.