I am making an instructional video for C# 4.0 for beginning programmers.
For every topic I introduce I include a practical example which the student could actually use, for instance, for the improved COM Interop functionality, I show how to create an Excel file and fill it with values from code.
For named and option parameters I show how you can create a logging method with 5 parameters but don't have to pass any if you don't want since they all have default values. So they see how calling methods is easier with this feature.
I would also like to introduce tuples as well if I can, but it seems that all the "practical examples" (as in this question: Practical example where Tuple can be used in .Net 4.0?) are very advanced. The learners that use the video learn OOP, LINQ, using generics, etc. but e.g. functional programming or "solving Problem 11 of Project Euler" are beyond the scope of this video.
Can anyone think of an example where tuples would actually be useful to a beginning programmer or some example where they could at least understand how they could be used by and advanced programmer? Their mechanics are quite straight-forward for a beginning programmer to grasp, I would just like to find an example so that the learner could actually use them for a practical reason. Any ideas?
Here's what I have so far, but it is just dry mechanics without any functionality:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//two ways to define them
var customer = new Tuple<int, string, string>(23, "Sam", "Smith");
var customer2 = Tuple.Create<int, string, string>(34, "James", "Allard");
//with type inference, more concise (only available with the Create keyword)
var customer3 = Tuple.Create(23, "John", "Hoopes");
//you can go up to eight, then you have to send in another tuple
var customer4 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10));
Console.WriteLine(customer.Item1);
Console.WriteLine(customer2.Item2);
Console.WriteLine(customer3.Item3);
Console.WriteLine(customer4.Rest.Item1.Item3);
Console.ReadLine();
}
}
}
Tuples are not necessarily the first topic I would tackle for beginner programmers ... however, there are some simple examples.
One that comes to mind is returning a value (which may actually be null) from a function that performs a search (or calculation), together with a boolean that indicates whether the result was found or not. It's an approach that avoids using out parameters, which can be cumbersome or problematic in certain scenarios (like LINQ queries):
public Tuple<string,bool> SearchDictionary( string searchKey )
{
string value;
bool wasFound = someDictionary.TryGetValue( searchKey, out value );
return new Tuple<string,bool( value, wasFound );
}
// since <null> is a legal value to store in the dictionary, we cannot
// use it to distinguish between 'value not found' and 'value is null'.
// the Tuple<string,bool>, however, does allow us to do so...
var result = SearchDictionary( "somekey" );
if( result.Item2 )
{
Console.WriteLine( result.Item1 );
}
Another example that I think is natural, is creating associations between two values without creating an explicit class for the purpose. For example, let's imagine we want to represent pairs of opponents who will play tennis matches. We could use:
// note the symmetry in the representation of opponents of a tennis match...
// if the relationship were asymmetrical, tuple may not be the best choice.
var playerA = new TennisPlayer("Serena Williams");
var playerB = new TennisPlayer("Venessa Williams");
var match = new Tuple<TennisPlayer,TennisPlayer>( playerA, playerB );
Creating a class for something like this can be avoided by using tuples instead.
A final example, is using tuples to represent composite keys in a dictionary. Since Tuple<>s can be compared to one another for equality, it becomes possible to do stuff like:
var complexDictionary =
new Dictionary<Tuple<string,int,decimal,DateTime>,string>();
complexDictionary.Add( new Tuple("USA",-4,1.671,DateTime.Now), "active" );
EDIT: One comment I would make when educating developers about the use of tuples, is that tuples should rarely (if ever) appear in the public interface of code you expect others to consume. As tools to simplify the internal implementation of a class or module, I think they're fine. But once you start passing them in or out of methods that developers consuming your code have to interact with, you run in the problem that tuples obscure the semantics of your API. It becomes hard for developers to interpret what Tuple<int,int> is supposed to mean. What do Item1 or Item2 mean in such a case? When you see yourself needing to pass tuples in or out of methods, you should strongly consider writing a class to encapsulate and clarify the relationship.
The best practical reason i can see is using them as temporary "classes". You want to associate multiple pieces of information, but not create yet another class structure to hold them.
They should be temporary, because if you're using them a lot, you should be going all the way and properly creating classes...
I can't think of a good specific example, i've mostly used them for small things, like temporary maps that need a single key but multiple pieces of information in the value...
I use them in place of private classes. The are great when used internally in a class.
Exposing them outside the class only led to confusion. I kept having to open the class to determine what was what.
What about on a login form? They see those all of the time.
var loginCredentials =
new Tuple<string, SecureString>(nameTextBox.Text, passwordTextBox.Text);
if (Login(loginCredentials))
Console.Writeline("Login - Success!");
else
Console.Writeline("Login - Failure");
...
public bool Login(Tuple<string, SecureString> loginCredentials)
{
return ...
}
Related
I am not new in the programming world, however I need help with understanding what is going on in this code. I DO understand the builder pattern and the Action delagete (does not return anything, but can take some parameters).
What bothers me a lot is below code:
0. var carBuilder = new CarBuilder().WithDoors(x => x.WithDoors(4)).Build();
1. public CarBuilder WithDoors(Action<DoorsBuilder> x)
2. {
3. var doorsBuilder = new DoorsBuilder();
4. x(doorsBuilder);
5. _car.AddDoors(doorsBuilder.Build());
6. return this;
7. }
What happens in line 4?
What do I actually pass in line 0 to WithDoors function?
Is is possible to rewrite that code in some simpler way (to get better understanding :))?
Code:
https://rextester.com/SIOV54215
What happens in line 4?
At line 4 the code calls the action delegate passing in the DoorBuilder which has been created in line 3, and in line 5 it adds the doors built using the door builder to the car being built by the CarBuilder. This is a fairly common pattern used in composite (or nested) builders. It looks much like a similar answer I gave to a question a number of years ago: Builder pattern with nested objects
What do I actually pass in line 0 to WithDoors function?
Herein is a problem, the naming of your methods is somewhat confusing, both the CarBuilder and the DoorBuilder has a method named WithDoors. I would have made the DoorBuilder have a method named NumberOfDoors making the code more readable, and more obvious what is happening:
var car = new CarBuilder().WithDoors(x => x.NumberOfDoors(4)).Build();
(Note the change of variable name; the result of this line is a (built) car NOT a carBuilder!)
Is is possible to rewrite that code in some simpler way (to get better understanding :))?
I wonder whether there is even a need for a nested builder here, perhaps there is as it becomes more complicated (say, setting the features of the door such as trim, electric wondows, etc etc) but as you have it right now the only thing you can build is the number of doors which could just as easily be put on the CarBuilder itself making the code:
var car = new CarBuilder().WithDoors(4).Build();
I am wondering about whether or not creating a list of an anonymous type is the best way to effectively create a list of multiple types as well as its effect on general performance and efficiency. Mainly I just want to know if there is a more standard way of doing List?
Situation
I every now and then find myself with a need to create a list that has multiple values each of a different type, List. Normally i would just resolve this with a Dictionary, but then there are the cases where i don't care about duplicated key values or need a 3rd (or rarely 4th) value. Usually this is for temporary list that just track something contained in a method like logging thrown errors and an associated value so that at the end of the method i can string together the messages for a log file or something.
What i have so far is this:
var list = new[] { new { RowNumber = 1, Message = "" } }.ToList();
list.Clear();//clears out the example used to create the anonymous type
list.Add(new { RowNumber = 10, Message = "bla bla" }); //adding to the list
I am debating on doing something like an extension or something to make this easier, but if the performance sucks or there is a better way, i would like to know.
I prefer to make a class. The IL just makes an anonymous class in native that gets called the same way as a normal class, so there is no performance hit associated with it. If you ever debug anonymous types, you'll notice the name has a long name like AnonymousTypes.Program+f__1
Creating a class improves the readability of your code IMO.
public class RowMessage
{
public int RowNumber { get; set; }
public string Message { get; set; }
}
You can also use Tuples, but even this is still unclear:
public void MyMethod()
{
Tuple<int, string> myTuple = new Tuple<int, string>(1, "hi");
List<Tuple<int, string>> myTupList = new List<Tuple<int, string>>();
myTupList.Add(myTuple);
}
I just experimented a little. Here's what I found:
Anonymous types are as good as anything else. I can't really say "anything," since I didn't try everything. But I can tell you that they're as good as Tuple<> and concrete types. This is logical, because underneath the covers, the compiler actually builds types for anonymous types. In essence, at runtime, they are just concrete types.
Your ToList call is redundant. This part's important. It's not super relevant to your immediate question, but looking at your example, you do new [] { ... }.ToList(). This forces a loop through the array after it's created. You'd be much better off using list initialization: new List<dynamic> { ... };. That's what I used in my examples.
I ran tests 10,000 times each for:
Anonymous type with array initializer (00:00:00.0050338 total)
Anonymous type with list initializer (00:00:00.0035599 total)
Tuple with list initializer (00:00:00.0025857 total)
Concrete type with list initializer (00:00:00.0041538 total)
Running them again would just mix it up. The only consistent result was that arrays were, unsurprisingly, slower than going directly to a list.
If you're going to make an extension method, you'll probably want to go with one of the latter two options. Anonymous types don't travel well outside of their scope, as I'm sure you know. The choice is yours between concrete types and tuples. I'd go with concrete if you're using it a lot and/or outside of the original method, and a tuple if it just needs to exist somewhere. That's really a design choice that I can't make for you.
Since you are talking about enriching Exceptioninformation it is worth to mention that the Exceptionclass implements a property called Data which is of type IDictionary and can be used to append additional information.
try
{
throw new FileNotFoundException{ Data ={ { "TEST", "Hello World" } } };
}
catch (Exception e)
{
Console.WriteLine(e.Data["TEST"]);
...
e.Data.Add("Whatever", DateTime.Now);
}
If you find yourself adding the same information lots of times, consider some HelperMethods that add certain information to a giving exception. This could also take care for duplicated keys which use some sort of numeric postfix that increments like fileName_1 and so on, you get the idea.
You can also create a standartized method of outputting those Information you provided yourself.
If you want a more Complex approach you can just simply use List but make the consumer of this list handle each kind of type. Which is basically the idea behind the DebuggerTypeProxy-Atrribute
So you can for example use some pattern like this:
foreach(var typeGroup in additionalInformation.GroupBy(item => item.GetType())
{
ITypedLogHandler handler = GetHandlerFor(typeGroup.Key);
handler.WriteLog(typeGroup);
}
In general the only reason I can think of this whole idea to beeing valid is some convenient debuggint/loggin approach. Anything else should really use strong typing.
My question is about whether what follows is an appropriate use of the dynamic keyword in C# 4.
I have some helper methods that provide a more useful representation of various objects than their standard ToString methods do, which I use for unit testing. Here is a simplified example:
public static string PrettyPrint<T>(IEnumerable<T> list)
{
return string.Join(", ", list);
}
// Needed because string is IEnumerable<char>, to prevent
// "Hello" -> "H, e, l, l, o"
public static string PrettyPrint(string s)
{
return s;
}
public static string PrettyPrint(object o)
{
return o.ToString();
}
I use them something like this:
public static void PrettyPrinting()
{
object[] things = { 1, "Hello", new int[] {1, 2, 3} };
foreach (dynamic item in things)
{
Console.WriteLine(PrettyPrint(item));
}
}
This produces the following output:
1
Hello
1, 2, 3
Notice that if I replace the dynamic keyword with object, I get the following (all the calls are routed through PrettyPrint(object)), which is what I am trying to avoid:
1
Hello
System.Int32[]
So my question is essentially is this a code smell or is it legitimate to cast an object to dynamic in this way?
So long as you don't abuse it, duck typing like this is part of the reason dynamic was added to the language.
As to your question, I'm not 100% sure as I don't know your teams style of coding. (I also see little comments ;) )
DuckTyping has it's uses - however a developer needs to know what they're doing before using it. Otherwise it's like running with scissors; it could be abused like other keywords in the C# system.
Personally, I'd rather see extension methods, but depending on the developer, his/her arguments and the documentation done I'd probably allow it.
The biggest reason for my hesitation (and this example is pretty tame to some of the ones I've seen online) is it stops you from finding issues at compile time. It requires more QA testing, a lot more boundary testing, and has a higher risk of failure.
Not an answer to the exact question, but I would say your code is not very OO, which is another smell.
Ideally you want to call item.PrettyPrint() and each item is supposed to return its representation, and override PrettyPrint.
Luckily, existing types can be extended with extension methods. They enable you to add the methods and that's what I would do instead.
If you still want to have the logic for the display of each type in one class, I would combine extension methods with the visitor pattern.
That said, I don't have C# environment so I can't test what I propose. Let me know if you try this, and if it works.
One of the common programming best practices is "define variables as close to where they are used as possible".
I use structs frequently to create code thats almost self documenting in places. However, C# forces me to define the struct outside the method. This breaks the aforementioned best practice - its basically creating an unwanted global variable type for the entire class.
Is it possible to define a local struct inside a method, just like a local variable, and if not, could you give me a window into the reasons the C# designers decided to prevent this?
Use Case
I'm converting part of a spreadsheet into C# code. I'd like to use local structs within the method to store temporary information in an organized manner, without having to resort to hundreds of separate variables that are global in scope.
Update 2016-August: C# 7.0 may have this feature!
As of 2016-Aug, apparently, this will be a feature in C# 7.0.
So the C# compiler team agreed - wow!
Update 2020-July: Now supported by C# and C++
C++ has always fully supported this. And it's fantastic.
C# 7.0 now has value tuples for a lightweight data structure with named fields. See answer from Ghost4Man.
I believe it's not permitted to define named types within a method. As to why, I'll have to speculate. If a type is not going to be used outside, then its existence probably cannot be justified.
You can however define anonymous type variables within a method. It will somewhat resembles structures. A compromise.
public void SomeMethod ()
{
var anonymousTypeVar = new { x = 5, y = 10 };
}
It is a little late but this is my solution for lists - using anonymous vars as the structs inside of methods:
var list = new[] { new { sn = "a1", sd = "b1" } }.ToList(); // declaring structure
list.Clear(); // clearing dummy element
list.Add(new { sn="a", sd="b"}); // adding real element
foreach (var leaf in list) if (leaf.sn == "a") break; // using it
Anonymous elements (sn and sd) are somehow read only.
Since C# 7.0, you can use value tuples if you want a lightweight data structure with named fields. They can be used not only locally inside methods, but also in parameters, returns, properties, fields, etc. You can use local functions to somewhat emulate struct methods.
var book = (id: 65, pageCount: 535); // Initialization A
(int id, int pageCount) book2 = (44, 100); // Initialization B
Console.WriteLine($"Book {book.id} has {book.pageCount} pages.");
(int id, int pageCount) = book; // Deconstruction into variables
Console.WriteLine($"Book {id} has {pageCount} pages.");
Here book is of type System.ValueTuple<int, int> (a generic struct).
You could do something like this using anonymous types. MSDN examples below:
var v = new { Amount = 108, Message = "Hello" };
or
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
Nowadays, you could also use a named tuple: https://learn.microsoft.com/en-us/dotnet/csharp/tuples
No, this is not possible. If you are using .net 4.0, you could use Tuple<T1, ..., Tn> to replicate such a thing.
I don't see the reason why you would need such a struct - just use variables with speaking names and this shouldn't be any problem at all. In combination with explicit declaration using the class names there is very little space for ambiguity.
You can define an anonymous type within your method and use it. The anonymous type will be readonly, so it gets you the immutability that is desired of structs. It will not explicitly be a struct, but it will be fully defined and contained within your method.
var myLocalType = new
{
SomeValue = "Foo",
SomeId = 14
};
it's not a struct, but mayme a var can help you out here?
var person = new {Name= "John", City = "London"};
it's strong typed so it will be compile time checked
You can create a dynamic type in c# 4.0 to accomplish this task, but its not exactly what you are looking for.
However I believe that the maximum of defining variables as close to where they are used is meant to mean where a variable is introduced into program flow not where the type is declared. I believe that most types have some ability to be reused creating in method types limits you ability to create reusable blocks of code that operates on common data.
I've been developing .net console applications using C# and have always just dictated what order parameters must be inserted in so that args[0] is always start date and args[1] is always end date, for example.
however I would like to move over to using named parameters so that any combination of parameters can be sent in any order, such as the typical "-sd" would prefix a start date.
I know I could parse through the args[] looking for "-" and then read the name and look the next position for the accompanying value, but before doing that wanted to see if there was any kind of baked in handling for this rather standard practice.
is there something like this out there already that could do as such:
DateTime startDate = (DateTime)((ConsoleParameters)args[])["sd"]
I'm using C# and .Net 4
There is nothing built into the core framework.
A lot of people think NDesk.Options is useful for this sort of thing. Check out this example (taken directly from the provided link):
string data = null;
bool help = false;
int verbose = 0;
var p = new OptionSet () {
{ "file=", v => data = v },
{ "v|verbose", v => { ++verbose } },
{ "h|?|help", v => help = v != null },
};
List<string> extra = p.Parse (args);
Yes, the "magic" is that this is a common problem and it has been adequately solved. So I recommend using an already written library to handle parsing command line arguments.
CommandLineParser has been great for me. It is reasonably documented and flexible enough for every type of command line argument I've wanted to handle. Plus, it assists with usage documentation.
I will say that I'm not the biggest fan of making a specific class that has to be adorned with attributes to use this library, but it's a minor point considering that it solves my problem. And in reality forcing that attributed class pushes me to keep that class separate from where my app actually retrieves it's settings from and that always seems to be a better design.
You can use NDesk.Options.
There is no such a thing as named parameters. "-sd" is just a choice for a specific application. It can be "/sd" as well. Or "sd=". Or whatever you want.
Since there are no named parameters, there is nothing inside .NET Framework which let you use the "-sd" syntax.
But you can quite easily build your own method to get a set of "named parameters" for your app.
Edit: or, even better, you can use an existing library, like suggested in other answers.
Edit: reading the answer by #Sander Rijken, I see that I was wrong: there were still an implementation of "-sd" syntax in .NET 4.0 before the release. But since it was dropped before the final release, the only ways are still to create your own method or to use an existing library.