Tuples in Functions
-
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
} -
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}A tuple is a reference object, so you need to create one using the
new
keyword. Try this :-public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return new Tuple<double, double>(Test_Val, Test_2);
}static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple<double,double> Result = Test(A, B, C);
Console.WriteLine("{0} {1}", Result.Item1 , Result.Item2 );
Console.ReadLine();
}When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
-
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}To create a
Tuple
, use one of the generic constructors (or the staticTuple.Create()
methods). I believe this is what you want to do:var result = new Tuple(a, b, c);
return new Tuple(test_val, test_2);[edit] To the univoter: Thank you for downvoting me because I was writing my reply at the same time as the first reponse (Wes) but didn't click the "Post Message" button in time. :doh: [/edit] /ravi
My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com
-
A tuple is a reference object, so you need to create one using the
new
keyword. Try this :-public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return new Tuple<double, double>(Test_Val, Test_2);
}static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple<double,double> Result = Test(A, B, C);
Console.WriteLine("{0} {1}", Result.Item1 , Result.Item2 );
Console.ReadLine();
}When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
-
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}You have the answer to your question, this is just a comment regarding the casing of your parameters, variables etc. There are some generally accepted rules for casing which makes code at a glance easier to read and understand. See here[^]. It is not normally recommended to use underscores, they don't add any clarity, and abbreviations are discouraged. Taking the above into consideration your code would look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace TestingFunctions
{
class Program
{
public static Tuple<double, double> Test(double value1, double value2, double value3)
{
double result1 = value1 + value2 + value3;
double result2 = 7;
return new Tuple(result1, result2);
}
static void Main(string[] args)
{
double a = 1, b = 2, c = 3;
Tuple result = Test(a, b, c);
Console.WriteLine("{0}", result);
}
}
}This makes no difference to the execution of the code, it is just a personal (or company if you code professionaly) matter of style. There are also many differing opinions on some finer points!
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) -
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}You can return more than 2 value from function. There are 2 way but I suggest you second one. 1. You can change your Method type to object[]. 2. Create a class and its member can be what you need to return. for example if you want to return 3 Double type value use these:
public class Result
{
public double FirstNumber { get; set; }
public double SecondNumber { get; set; }
public double ThirdNumber { get; set; }
// And you can create more ....
}Then in your function:
public static Result Do(params double[] numbers)
{
Result result = new Result();result.FirstNumber = numbers\[0\] - numbers\[1\]; foreach (double number in numbers) result.SecondNumber += number; return result;
}
Meysam
-
You have the answer to your question, this is just a comment regarding the casing of your parameters, variables etc. There are some generally accepted rules for casing which makes code at a glance easier to read and understand. See here[^]. It is not normally recommended to use underscores, they don't add any clarity, and abbreviations are discouraged. Taking the above into consideration your code would look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace TestingFunctions
{
class Program
{
public static Tuple<double, double> Test(double value1, double value2, double value3)
{
double result1 = value1 + value2 + value3;
double result2 = 7;
return new Tuple(result1, result2);
}
static void Main(string[] args)
{
double a = 1, b = 2, c = 3;
Tuple result = Test(a, b, c);
Console.WriteLine("{0}", result);
}
}
}This makes no difference to the execution of the code, it is just a personal (or company if you code professionaly) matter of style. There are also many differing opinions on some finer points!
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)DaveyM69, no personal attack intended, but I think it is generally unhelpful, and off-topic, to respond to a poster, struggling to get his, or her, head around a "best practice" technical strategy, with a "sermon" on variable-naming, and code-style: a topic on which there are many (widely debated) points of view. Consider the "religious wars" over just use of indentation, and/or, the virtues of the location of a block-open curly brace, and block-close curly brace: K&R, where the block-start curly brace follows the final close-parens of the argument list (usually preceded by a space) vs. the practice of adding a line break after the end of the argument list, then the open-curly-brace, followed by another line-break, and then use of indentation. Perhaps long ago, the very limited memory available in developer's machines made minimizing white-space desirable: but that is no longer the case. The fact is that if you get employed in a working team with a substantial code-base, you will have to adopt to their notation and casing conventions. And, some code transformations, such as KR style brace use <==> line-break-indent style, are easily done with very simple Regex expressions. And, conventions, like use of braces, may have very different behaviors from language to language: example: JavaScript: variables declared inside {} are not locally-scoped and disposed; they are global. For this reason, I voted your response a #1. best, Bill
"One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut
-
DaveyM69, no personal attack intended, but I think it is generally unhelpful, and off-topic, to respond to a poster, struggling to get his, or her, head around a "best practice" technical strategy, with a "sermon" on variable-naming, and code-style: a topic on which there are many (widely debated) points of view. Consider the "religious wars" over just use of indentation, and/or, the virtues of the location of a block-open curly brace, and block-close curly brace: K&R, where the block-start curly brace follows the final close-parens of the argument list (usually preceded by a space) vs. the practice of adding a line break after the end of the argument list, then the open-curly-brace, followed by another line-break, and then use of indentation. Perhaps long ago, the very limited memory available in developer's machines made minimizing white-space desirable: but that is no longer the case. The fact is that if you get employed in a working team with a substantial code-base, you will have to adopt to their notation and casing conventions. And, some code transformations, such as KR style brace use <==> line-break-indent style, are easily done with very simple Regex expressions. And, conventions, like use of braces, may have very different behaviors from language to language: example: JavaScript: variables declared inside {} are not locally-scoped and disposed; they are global. For this reason, I voted your response a #1. best, Bill
"One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut
I believe some 'generally accepted' conventions should be followed as early as possible as code legibility and comprehension can be greatly increased for both the individual and anyone reviewing the code. I did point out there were differing opinions too and also mentioned that companies have their own styles. In my opinion it was far from a sermon; One sentence followed by a code example does not a sermon make.
BillWoodruff wrote:
For this reason, I voted your response a #1
That is your prerogative, but perhaps somewhat extreme? No matter, CP reputation points are the least of my concerns in life!
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) -
You can return more than 2 value from function. There are 2 way but I suggest you second one. 1. You can change your Method type to object[]. 2. Create a class and its member can be what you need to return. for example if you want to return 3 Double type value use these:
public class Result
{
public double FirstNumber { get; set; }
public double SecondNumber { get; set; }
public double ThirdNumber { get; set; }
// And you can create more ....
}Then in your function:
public static Result Do(params double[] numbers)
{
Result result = new Result();result.FirstNumber = numbers\[0\] - numbers\[1\]; foreach (double number in numbers) result.SecondNumber += number; return result;
}
Meysam
Why is your result class better than using
Tuple
? Usingparams double[]
may be a good idea for extensibility. If doing this however, it's important to check thatnumbers
isn'tnull
, and then check it'sLength
before using indexers otherwise some nasty exceptions may get thrown at some point.Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) -
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}OK, I realise I suggested the
Tuple
thing in the thread below. What you have will work (when fixed) and is arguably correct. However if the return value "means" something as a pair it would be better in a language like C# creating aclass
orstruct
to contain them. One rule of thumb is if you can give your return "thing" a sensible name. Let's say for the sake of argument the return values represent a x/y co-ordinate pair. If this were the case then you'd be better of creating a class or struct. If the values are really two results from a calculation (as you have in your example) a tuple is good. The point of the class is that it gives semantic meaning to your program, which developers that follow you can understand. [Edit] This came to me after reading Bill's reply below. One thing that you also need to consider with the tuple is that it is reliant on the code consuming the class knowing what order the values were put in (and your code putting them in the right order), if you were returning say astring
and adouble
there would be less problem. That said creating a container class or struct the values would be explicitly named, reducing the potential for error. Hopefully this isn't too confusing, getting to grips with programming is quite a task. This is a good read[^] if you are just starting out, it isn't as negative as the first few paragraphs suggest.Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-
A Dead ringer for Kate Winslett[^] -
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}Between the responses to your first post, the responses to this post, and the (strangely out of place) discussion on the Lounge[^], you have a of ideas, and alternate strategies for using Tuples. I want to respond directly to your question about using Tuples. In my opinion, they can best be described as a "bag of pairs" where, for every pair in the bag: the first element, of the pair, is a Type; and, the second element is a value of that Type. And, do keep in mind that Tuples were introduced in .NET 4.0. So, they are most appropriate, imho, if you need to return a bunch of different types: if every Type in your Tuple elements is the same: then use one of the other strategies, or a generic List<Type>, or another method. Let me try and make this concrete for you: you can download this project (with source) compiled against .NET 4.0 here:[^]. 1. create a simple 'WinForms application: drop a 'CheckBox, a 'DateTimePicker, a 'TextBox, and a 'NumericUpDown[1] on the main Form. 2. put two 'Buttons on the Form: title the first 'Button "Save Tuple," and the second "Restore Tuple." Now let's look at what happens using a real Tuple in action: (attention: code-style obsessive-compulsives: I am using extra indentation, and line-breaks, here for clarity for the OP, it would not be my standard style): 1. first you declare a Form-scoped variable of Type Tuple for re-use:
private Tuple<CheckState, DateTime, string, decimal> _fourTuple;
1. You run the application, change the values of any of the four controls any way you like, and click the "Save Tuple" button: this code executes:
private void SaveTupleButtonClick(object sender, EventArgs e)
{
_fourTuple = Tuple.Create
(
checkBox1.CheckState,
dateTimePicker1.Value,
textBox1.Text,
numericUpDown1.Value
);
}Here I am using the static Tuple.Create method, which was introduced in .NET FrameWork 4.0, to save some typing; it's exactly the same as if I wrote the fuller version:
private void SaveTupleButton_Click(object sender, EventArgs e)
{
_fourTuple = new Tuple
(
checkBox1.CheckState,
dateTimePicker1.Value,
textBox1.Text,
numericUpDown1.Va -
Why is your result class better than using
Tuple
? Usingparams double[]
may be a good idea for extensibility. If doing this however, it's important to check thatnumbers
isn'tnull
, and then check it'sLength
before using indexers otherwise some nasty exceptions may get thrown at some point.Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) -
Between the responses to your first post, the responses to this post, and the (strangely out of place) discussion on the Lounge[^], you have a of ideas, and alternate strategies for using Tuples. I want to respond directly to your question about using Tuples. In my opinion, they can best be described as a "bag of pairs" where, for every pair in the bag: the first element, of the pair, is a Type; and, the second element is a value of that Type. And, do keep in mind that Tuples were introduced in .NET 4.0. So, they are most appropriate, imho, if you need to return a bunch of different types: if every Type in your Tuple elements is the same: then use one of the other strategies, or a generic List<Type>, or another method. Let me try and make this concrete for you: you can download this project (with source) compiled against .NET 4.0 here:[^]. 1. create a simple 'WinForms application: drop a 'CheckBox, a 'DateTimePicker, a 'TextBox, and a 'NumericUpDown[1] on the main Form. 2. put two 'Buttons on the Form: title the first 'Button "Save Tuple," and the second "Restore Tuple." Now let's look at what happens using a real Tuple in action: (attention: code-style obsessive-compulsives: I am using extra indentation, and line-breaks, here for clarity for the OP, it would not be my standard style): 1. first you declare a Form-scoped variable of Type Tuple for re-use:
private Tuple<CheckState, DateTime, string, decimal> _fourTuple;
1. You run the application, change the values of any of the four controls any way you like, and click the "Save Tuple" button: this code executes:
private void SaveTupleButtonClick(object sender, EventArgs e)
{
_fourTuple = Tuple.Create
(
checkBox1.CheckState,
dateTimePicker1.Value,
textBox1.Text,
numericUpDown1.Value
);
}Here I am using the static Tuple.Create method, which was introduced in .NET FrameWork 4.0, to save some typing; it's exactly the same as if I wrote the fuller version:
private void SaveTupleButton_Click(object sender, EventArgs e)
{
_fourTuple = new Tuple
(
checkBox1.CheckState,
dateTimePicker1.Value,
textBox1.Text,
numericUpDown1.VaVote of 5: Coherent, well though out and correct. I'd have been tempted to suggest we also have n-Tuple generics(ish), which if I had my way I'd have called then nuples.
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-
A Dead ringer for Kate Winslett[^] -
Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Testing_Functions
{
class Program
{
public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
{
Double Test_Val = Val1 + Val2 + Val3;
Double Test_2 = 7;
return Tuple(Test_Val, Test_2);
}
static void Main(string[] args)
{
Double A = 1, B = 2, C = 3;
Tuple Result = Test(A,B,C);
Console.WriteLine("{0}", Result);
}
}
}Leppie wrote[^] re: the discussion of the use of Tuples (on the Lounge):
"Anonymous classes handle most of these cases and cleaner in my opinion. Who knows what Item0 and Item1 and Item2 is?"
.Of course Leppie is absolutely right: Tuple elements cannot be accessed by index; they cannot be foreach iterated, and, the following "legal" way to find out, at run-time, what Type an Item1 ... Item#n is, for example: "_fourTuple.Item1.GetType();" is something that would make me gag if I saw it in "real code." The main reason I am writing this is to ask Leppie to please reply with an example of the use of anonymous classes, which interests me very much, and I think will add value to this discussion. thanks, Bill
"One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut
-
Between the responses to your first post, the responses to this post, and the (strangely out of place) discussion on the Lounge[^], you have a of ideas, and alternate strategies for using Tuples. I want to respond directly to your question about using Tuples. In my opinion, they can best be described as a "bag of pairs" where, for every pair in the bag: the first element, of the pair, is a Type; and, the second element is a value of that Type. And, do keep in mind that Tuples were introduced in .NET 4.0. So, they are most appropriate, imho, if you need to return a bunch of different types: if every Type in your Tuple elements is the same: then use one of the other strategies, or a generic List<Type>, or another method. Let me try and make this concrete for you: you can download this project (with source) compiled against .NET 4.0 here:[^]. 1. create a simple 'WinForms application: drop a 'CheckBox, a 'DateTimePicker, a 'TextBox, and a 'NumericUpDown[1] on the main Form. 2. put two 'Buttons on the Form: title the first 'Button "Save Tuple," and the second "Restore Tuple." Now let's look at what happens using a real Tuple in action: (attention: code-style obsessive-compulsives: I am using extra indentation, and line-breaks, here for clarity for the OP, it would not be my standard style): 1. first you declare a Form-scoped variable of Type Tuple for re-use:
private Tuple<CheckState, DateTime, string, decimal> _fourTuple;
1. You run the application, change the values of any of the four controls any way you like, and click the "Save Tuple" button: this code executes:
private void SaveTupleButtonClick(object sender, EventArgs e)
{
_fourTuple = Tuple.Create
(
checkBox1.CheckState,
dateTimePicker1.Value,
textBox1.Text,
numericUpDown1.Value
);
}Here I am using the static Tuple.Create method, which was introduced in .NET FrameWork 4.0, to save some typing; it's exactly the same as if I wrote the fuller version:
private void SaveTupleButton_Click(object sender, EventArgs e)
{
_fourTuple = new Tuple
(
checkBox1.CheckState,
dateTimePicker1.Value,
textBox1.Text,
numericUpDown1.VaWhile anonymous classes will not here, in this situation based on the amount of usage and 'decoration' required, a concrete class IMO would be a better option. Remember you only have to write it once.
struct State
{
public CheckState Value;
public DateTime When;
public string By;
public decimal Amount;
}A struct already implements hashcode and equality too. Now imagine you need an extra field. In the case of a class/struct, no problem, but your Tuple will require changes across the board, even if you just add it to the end.
-
While anonymous classes will not here, in this situation based on the amount of usage and 'decoration' required, a concrete class IMO would be a better option. Remember you only have to write it once.
struct State
{
public CheckState Value;
public DateTime When;
public string By;
public decimal Amount;
}A struct already implements hashcode and equality too. Now imagine you need an extra field. In the case of a class/struct, no problem, but your Tuple will require changes across the board, even if you just add it to the end.
Thanks, Leppie, for "weighing in here:" your comment on anonymous classes has lead me to some interesting technical geography. Of course, I am still eager to here how you use anonymous classes :) I've been reading, on various web-sources, mainly StackOverFlow, discussions of anonymous classes: the problem with SO is that while the OP may mention the words "anonymous classes," the discussion soon turns, it seems, to anonymous types, and use of 'dynamic, and 'var. This SO thread was interesting for the sheer volume of responses and debates:"A generic list of anonymous class"[^]. Probably the two most interesting (and exotic) discussions I found were by Jon Skeet: "Horrible grotty hack: returning an anonymous type instance"[^], and on a site called DevCurry: "Look Ma! No Classes – Creating Generic List(T) collection of Anonymous Types and calling Extension Methods"[^]. In the comments section of the Skeet article is this wonderful exchange between Jon and one "Erik:" # re: Horrible grotty hack: returning an anonymous type instance "This is one of those examples where relying on internal implementations can bite you, I imagine - since anonymous types are by design not supposed to leave private scope, the compiler team is free to do whatever they want with the actual implementation. Thanks for the brain-twitch, though, Jon. =) Friday, January 09, 2009 12:21 PM by Erik" # re: Horrible grotty hack: returning an anonymous type instance "@Erik: No, it's not implementation-dependent. The compiler-generated name is, but the language spec guarantees that two anonymous object creation expressions using the same property names and compile-time types within the same assembly will create instances of the same type. See section 7.5.10.6 of the C# 3.0 spec. Friday, January 09, 2009 1:48 PM by skeet" best, Bill
"One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut
-
Thanks, Leppie, for "weighing in here:" your comment on anonymous classes has lead me to some interesting technical geography. Of course, I am still eager to here how you use anonymous classes :) I've been reading, on various web-sources, mainly StackOverFlow, discussions of anonymous classes: the problem with SO is that while the OP may mention the words "anonymous classes," the discussion soon turns, it seems, to anonymous types, and use of 'dynamic, and 'var. This SO thread was interesting for the sheer volume of responses and debates:"A generic list of anonymous class"[^]. Probably the two most interesting (and exotic) discussions I found were by Jon Skeet: "Horrible grotty hack: returning an anonymous type instance"[^], and on a site called DevCurry: "Look Ma! No Classes – Creating Generic List(T) collection of Anonymous Types and calling Extension Methods"[^]. In the comments section of the Skeet article is this wonderful exchange between Jon and one "Erik:" # re: Horrible grotty hack: returning an anonymous type instance "This is one of those examples where relying on internal implementations can bite you, I imagine - since anonymous types are by design not supposed to leave private scope, the compiler team is free to do whatever they want with the actual implementation. Thanks for the brain-twitch, though, Jon. =) Friday, January 09, 2009 12:21 PM by Erik" # re: Horrible grotty hack: returning an anonymous type instance "@Erik: No, it's not implementation-dependent. The compiler-generated name is, but the language spec guarantees that two anonymous object creation expressions using the same property names and compile-time types within the same assembly will create instances of the same type. See section 7.5.10.6 of the C# 3.0 spec. Friday, January 09, 2009 1:48 PM by skeet" best, Bill
"One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut
Quote:
I am still eager to here how you use anonymous classes
In the aforementioned case, it would be impossible :) The rest of the possible cases is indeed described by Jon Skeet, and while he calls them a 'hack', any of those ways should be preferred over tuples (IMO).
-
Leppie wrote[^] re: the discussion of the use of Tuples (on the Lounge):
"Anonymous classes handle most of these cases and cleaner in my opinion. Who knows what Item0 and Item1 and Item2 is?"
.Of course Leppie is absolutely right: Tuple elements cannot be accessed by index; they cannot be foreach iterated, and, the following "legal" way to find out, at run-time, what Type an Item1 ... Item#n is, for example: "_fourTuple.Item1.GetType();" is something that would make me gag if I saw it in "real code." The main reason I am writing this is to ask Leppie to please reply with an example of the use of anonymous classes, which interests me very much, and I think will add value to this discussion. thanks, Bill
"One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut