473,657 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question regarding generics and type constraints

I'm new to Generics (years and years of VS.NET 2003 development, but very
little .NET 2.0+). I have some routines for conversion from RGB to different
color spaces and back. I would like the routines to support, at least, byte,
int, and double types without having to create different versions of the
routines. Is there any way to do this with generics?

The problem is, if I do something like this:

public static void RGB_to_YIQ<T>(T[] R, T[] G, T[] B, T[] Y, T[] I, T[] Q)
{
Y[index] = 0.299 * R[index] + 0.587 * G[index] + 0.114 * B[index];
...
}

I get an error: "Operator '*' cannot be applied to operands of type 'double'
and 'T'"

Like I said, I'm a newb to the whole generics thing. I read the "Constraint s
on Type Parameters" stuff using "where" in MSDN, but I'm not sure how I can
use that, if I can.

Thanks.

Feb 13 '08 #1
5 1453
There is an issue with using operators with generics.

If you have .NET 3.5, I have a full and easy solution to this problem here:

http://www.pobox.com/~skeet/csharp/g...operators.html
(also briefly explains the problem)

Note the "usage" page, and the download via "MiscUtil" (the two links in the
opening lines).

Basically, you can various things involving Operator.Multip ly(x,y),
Operator.Add(x, y) - you might also need Operator.Conver t<float,T(or
something) to handle your literals (0.299 etc).

I'm about to run away for a few hours, but post back if you want more
info...

Marc
Feb 13 '08 #2
Marc,

Interesting stuff. This code is generally used in performance-critical areas
and it looks like your code would add a good bit of overhead converting all
the operators to method calls, though I don't know enough about it to be
sure.

If it's going to impede performance significantly, I'll just stick to
separate versions of the code.

"Marc Gravell" <ma**********@g mail.comwrote in message
news:OG******** ******@TK2MSFTN GP06.phx.gbl...
There is an issue with using operators with generics.

If you have .NET 3.5, I have a full and easy solution to this problem
here:

http://www.pobox.com/~skeet/csharp/g...operators.html
(also briefly explains the problem)

Note the "usage" page, and the download via "MiscUtil" (the two links in
the opening lines).

Basically, you can various things involving Operator.Multip ly(x,y),
Operator.Add(x, y) - you might also need Operator.Conver t<float,T(or
something) to handle your literals (0.299 etc).

I'm about to run away for a few hours, but post back if you want more
info...

Marc

Feb 13 '08 #3
Below is a link that may help you understand why you are having this
problem:
http://www.codeproject.com/KB/cs/genericnumerics.aspx

"Fredo" <fr***@hotmail. comwrote in message
news:i-*************** *************** @giganews.com.. .
I'm new to Generics (years and years of VS.NET 2003 development, but very
little .NET 2.0+). I have some routines for conversion from RGB to
different color spaces and back. I would like the routines to support, at
least, byte, int, and double types without having to create different
versions of the routines. Is there any way to do this with generics?

The problem is, if I do something like this:

public static void RGB_to_YIQ<T>(T[] R, T[] G, T[] B, T[] Y, T[] I, T[] Q)
{
Y[index] = 0.299 * R[index] + 0.587 * G[index] + 0.114 * B[index];
...
}

I get an error: "Operator '*' cannot be applied to operands of type
'double' and 'T'"

Like I said, I'm a newb to the whole generics thing. I read the
"Constraint s on Type Parameters" stuff using "where" in MSDN, but I'm not
sure how I can use that, if I can.

Thanks.

Feb 13 '08 #4
Interesting stuff. This code is generally used in performance-critical areas
and it looks like your code would add a good bit of overhead converting all
the operators to method calls, though I don't know enough about it to be
sure.
It actually inlines pretty well, especially for non-nullable types -
but if this is 100% performance critical, then I'd have separate
Int32, Byte, etc methods; but in all seriousness - the slowdown isn't
as bad as you might expect, since this the expression is compiled once
(only) per type and re-used. You lose a bit of time in delegate
invoke, but thats about it.

Marc
Feb 13 '08 #5
"TestDecima l"

it was just the method name that was wrong; this should have been
TestDouble; results stand "as is" though.

Basically, I started with decimal and then moved to double because
that was in your list; I forgot to rename.
Feb 13 '08 #6

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

Similar topics

11
3990
by: andrew queisser | last post by:
I've read some material on the upcoming Generics for C#. I've seen two types of syntax used for constraints: - direct specification of the interface in the angle brackets - where clauses I looked at the files in the Gyro download but I couldn't find any mention of constraints. Can anyone enlighten me what the current status is and what we can expect when Generics are released? Thanks,
10
2595
by: Ruediger Klaehn | last post by:
Sorry about the harsh language, but I have to vent my anger to somebody who actually understands what I am talking about. Complaining to my girlfriend is not going to produce any meaningful results other than straining our relationship... I just downloaded Visual C# Express Edition to mess with .NET 2.0 generics. Being a numerically inclined developer, the first thing I wanted to write was a generic complex number class. I also have some...
3
1481
by: Pierre Y. | last post by:
Hi, I've just read that article : http://msdn.microsoft.com/library/en-us/dnvs05/html/csharp_generics.asp I'm asking something. Why are generics constraints not been implemented using Attributes instead of "where..." syntax ? Regards,
16
1826
by: bigtexan | last post by:
I would like to do the following and cannot figure it out. public class A<T> { public delegate T GetValueDelegate(A<T> var); public GetValueDelegate GetValue = new GetValueDelegate(B.GetValue); } public class B {
3
1952
by: Marshal | last post by:
/////////////////////////////////////////////////////////////////////////////////////////////// /// CONSTRAINTS ON GENERICS //////////////////////////////////////////////////// public class Node<T> where T:IComparable<T> I don't like the syntax, and would prefer something that groups the constraint along with the type that it governs them, as depicted in this suggestion:
17
1930
by: atgraham | last post by:
Here is the "lead C# architect" attempting to impugn C++ templates (bottom of the page). http://www.artima.com/intv/generics2.html (bottom of the page) (Full article begins at http://www.artima.com/intv/generics.html) I think every employee at Micrsoft must be required to take a class in "FUD marketing" before speaking with anyone outside the company. I think the term "money oriented programming" is suitable here.
11
2474
by: hammad.awan_nospam | last post by:
Hello, I'm wondering if it's possible to do the following with Generics: Let's say I have a generic member variable as part of a generic class like this: List<DLinqQuery<TDataContext>> _queries; where DLinqQuery is a generic class that takes a type parameter
6
5451
by: =?Utf-8?B?UXVhbiBOZ3V5ZW4=?= | last post by:
I am trying to create a generics class with multiple constrains, as follows: public class KeyHandler<Twhere T : TextBoxBase, ComboBox When I try that, the compiler would complain: The class type constraint 'System.Windows.Forms.ComboBox' must come before any other constraints If I switch place of ComboBox with TextBoxBase, it would gripe:
5
2236
by: teel | last post by:
Hi there, I'm trying to apply "less than" and "more than" operators on the Generics (class template-like) type objects. Below is the code of my class representing a parameter that can be any type, but only if it's float or int the comparison results in true/false-like result, else its INVALID. I get error: Operator '<' cannot be applied to operands of type 'T' and 'T' at line: set { m_Value = value < m_MinValue ? m_MinValue : (value >...
0
8421
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
8325
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8742
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7354
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...
0
5643
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
4173
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...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
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
2
1734
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.