What value do you think named and default parameters will add in C#.Net 4.0?
What would be a good use for these (that hasn't already been achieved with overloading and overriding)?
It can make constructors simpler, especially for immutable types (which are important for threading) - see here for a full discussion. Not as nice as it should be perhaps, but nicer than having lots of overloads. You obviously can't use object initializers with immutable objects, so the usual:
new Foo {Id = 25, Name = "Fred"}
isn't available; I'll settle for:
new Foo (Id: 25, Name: "Fred")
This can be extended to the general idea of simplifying overloads, but in most cases I'd prefer overloads that advertise the legal combinations. Constructors are a bit different, IMO, since you are just (typically) defining the initial state.
The COM side of things is also important to a lot of people, but I simply don't use much COM interop - so this isn't as important to me.
Edit re comments; why didn't they just use the same syntax that attributes use? Simple - it can be ambiguous with other members / variables (which isn't an issue with attributes); take the example:
[XmlElement("foo", Namespace = "bar")]
which uses one regular parameter (to the ctor, "foo"), and one named assignment. So suppose we use this for regular named arguments:
SomeMethod("foo", SecondArg = "bar");
(which could also be a constructor; I've used a method for simplicity)
Now... what if we have a variable or a property called SecondArg? This would be ambiguous between using SecondArg as a named argument to SomeMethod, and assigning "bar" to SecondArg, and passing "bar" as a regular argument.
To illustrate, this is legal in C# 3.0:
static void SomeMethod(string x, string y) { }
static void Main()
{
string SecondArg;
SomeMethod("foo", SecondArg = "bar");
}
Obviously, SecondArg could be a property, field, varialble, etc...
The alternative syntax doesn't have this ambiguity.
Edit - this section by 280Z28: Sorry for adding this here, but it's not really a unique answer and it's too long for the comments and includes code. You hinted at the ambiguity but your example didn't highlight the deciding case. I think the example you gave points out something that could be confusing, but the required {} around object initializers prevents an underlying syntactical ambiguity. My explanation for the following code is embedded as the multi-line block comment.
[AttributeUsage(AttributeTargets.Class)]
public sealed class SomeAttribute : Attribute
{
public SomeAttribute() { }
public SomeAttribute(int SomeVariable)
{
this.SomeVariable = SomeVariable;
}
public int SomeVariable
{
get;
set;
}
}
/* Here's the true ambiguity: When you add an attribute, and only in this case
* there would be no way without a new syntax to use named arguments with attributes.
* This is a particular problem because attributes are a prime candidate for
* constructor simplification for immutable data types.
*/
// This calls the constructor with 1 arg
[Some(SomeVariable: 3)]
// This calls the constructor with 0 args, followed by setting a property
[Some(SomeVariable = 3)]
public class SomeClass
{
}
It will help to dodge the problem of providing a decent API to work with Office applications! :)
Some parts of the Office API are okay, but there are edge cases that were clearly designed for use from a language with optional/named parameters. So that's why C# has to have them.
Optional parameters also avoid the problem where classes provide dozens of methods that are just variations on the arguments accepted.
Consider the Exception class. Instead of one constructor with optional arguments, it has four constructors for each combination of 'has message', and 'has inner exception'. That's alright, but now consider what happens if you provide a null value to a constructor taking an innerException? Does it act exactly like the constructor with with no innerException parameter, sortof like the constructor with no innerException parameter, or does it throw a null reference exception?
A single constructor with 2 optional parameters would have made it more obvious that passing a null innerException was equivalent to not including it at all. A perfect place for default arguments.
Also don't forget that now every derived Exception class also has to include 4 constructors, which is a pointless hassle.
It will make COM interop a lot easier.
Until C# 4 VB.Net was a much better language for interop. Without defaults you have massive lists of dummy ref parameters in C#.
Brevity of code is the obvious one that springs to mind. Why define several overloads when you can define one function. Also, though, if you have two identically typed parameters, it isn't always possible to construct the full set of overloads you might need.
Also this doesn't compile:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
public MyAttribute(object a = null)
{
}
}
class Test
{
[My] // [My(a: "asd")]
int prop1 { get; set; }
}
while this does:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
public MyAttribute()
{
}
public object a { get; set; }
}
class Test
{
[My] // [My(a=null)]
int prop1 { get; set; }
}
Related
So, I have an abstract class with a method with 3 parameters, which is overridden in a particular base class.
The abstract method is in the following form:
internal override void SummonJonSkeet(string dumbQuestion, int a, int b)
{
// Call upon Jon Skeet and his followers to correct my ignorant ways.
}
In most of the subclasses that implement the given method, all 3 parameters are needed to produce a correct result. However, in this particular instance the only valid values of a and b are 0.
Currently what I am doing is just ignoring their values within the method, and providing a warning in the documentation comment for the method, but this just feels...wrong.
There has to be a better way than forcing a programmer (well, me) to insert junk arguments into the method call just to make the compiler happy, while still requiring the use of these arguments for every other subclass that implements the method.
Maybe this is a dumb question, since my solution works, but it just feels like it's not a smart way to do it. For example, some idiot (probably me) shouldn't be able to come along and cause an unhandled exception by inserting some ridiculous number into an argument that isn't used in the first place.
Another option (given that you mentioned the parameters are really coordinates that may or may not be used) could be just to make the values nullable with default values of null.
internal override void SummonJonSkeet(string dumbQuestion, int? a = null, int? b = null)
You'd have to match the abstract definition as well, but this shows the approach.
This allows the sub-classes to call SummonJonSkeet("my question") or SummonJonSkeet("my question", 1, 2) based on its implementation. The sub-classes that expect the values can then check a.HasValue or a != null to throw errors when values does not exist for parameters when expected to have values. To get the primitive value, just call a.Value.
You might consider an approach that creates a class for the parameters (assuming you might need these parameters to have specific names or various types).
public class BasicQuestionParameters { public string DumbQuestion {get;set;} }
Then, you could modify your abstract class to be generic that requires a type that is of the type BasicQuestionParameters.
public abstract class SummonBase<TParams> where TParams : BasicQuestionParameters
{
abstract void SummonJobSkeet(TParams question);
}
Now you can implement your sub-classes to define what type of question parameters it needs as long as they start from your basic one.
public class MySummonBasic : SummonBase<BasicQuestionParameters>
{
internal override void SummonJonSkeet(BasicQuestionParameters question) {...}
}
The benefit here is now you can add additional parameters by inheritance:
public class HardQuestionParameters : BasicQuestionParameters
{
public int A {get;set;}
public int B {get;set;}
}
And then use this in only the sub-classes that need the more refined type:
public class HardSummon : SummonBase<HardQuestionParameters>
{
internal override void SummonJonSkeet(HardQuestionParameters question) {...}
}
Now each sub-class has exactly the parameters it needs and nothing more or less. This approach has the added benefit that if you find a set of sub-classes need an additional parameter (C), you can do it by only needing to update the sub-classes that need to use the additional parameter. No need to touch all the other sub-classes that just need the basic parameters.
If you do not use the int parameters, you can change the signature of the virtual method to:
internal override void SummonJonSkeet(string dumbQuestion, params int[] values)
{
//...
}
In this way you can call it with only the string parameter, like this:
this.SummonJonSkeet(dumbQuestion);
I'm using a 3rd party's set of webservices, and I've hit a small snag. Before I manually make a method copying each property from the source to the destination, I thought I'd ask here for a better solution.
I've got 2 objects, one of type Customer.CustomerParty and one of type Appointment.CustomerParty. The CustomerParty objects are actually property and sub-oject exactly the same. But I can't cast from 1 to the other.
So, I need to find a certain person from the webservice. I can do that by calling Customer.FindCustomer(customerID) and it returns a Customer.CustomerParty object.
I need to take that person that I found and then use them a few lines down in a "CreateAppointment" request. Appointment.CreateAppointment takes an appointment object, and the appointment object contains a CustomerParty object.
However, the CustomerParty object it wants is really Appointment.CustomerParty. I've got a Customer.CustomerParty.
See what I mean? Any suggestions?
Why don't you use AutoMapper? Then you can do:
TheirCustomerPartyClass source = WebService.ItsPartyTime();
YourCustomerPartyClass converted =
Mapper.Map<TheirCustomerPartyClass, YourCustomerPartyClass>(source);
TheirCustomerPartyClass original =
Mapper.Map<YourCustomerPartyClass, TheirCustomerPartyClass>(converted);
As long as the properties are identical, you can create a really simple map like this:
Mapper.CreateMap<TheirCustomerPartyClass, YourCustomerPartyClass>();
Mapper.CreateMap<YourCustomerPartyClass, TheirCustomerPartyClass>();
This scenario is common when writing domain patterns. You essentially need to write a domain translator between the two objects. You can do this several ways, but I recommend having an overridden constructor (or a static method) in the target type that takes the service type and performs the mapping. Since they are two CLR types, you cannot directly cast from one to the other. You need to copy member-by-member.
public class ClientType
{
public string FieldOne { get; set; }
public string FieldTwo { get; set; }
public ClientType()
{
}
public ClientType( ServiceType serviceType )
{
this.FieldOne = serviceType.FieldOne;
this.FieldTwo = serviceType.FieldTwo;
}
}
Or
public static class DomainTranslator
{
public static ServiceType Translate( ClientType type )
{
return new ServiceType { FieldOne = type.FieldOne, FieldTwo = type.FieldTwo };
}
}
I'm using a 3rd party's set of
webservices...
Assuming you can't modify the classes, I'm not aware of any way you can change the casting behavior. At least, no way that isn't far, far more complicated than just writing a CustomerToAppointmentPartyTranslator() mapping function... :)
Assuming you're on a recent version of C# (3.5, I believe?), this might be a good candidate for an extension method.
Have you looked at adding a conversion operator to one of the domain classes to define an explicit cast. See the msdn documentation here.
Enjoy!
A simple and very fast way of mapping the types is using the PropertyCopy<TTarget>.CopyFrom<TSource>(TSource source)
method from the MiscUtil library as described here:
using MiscUtil.Reflection;
class A
{
public int Foo { get; set; }
}
class B
{
public int Foo { get; set; }
}
class Program
{
static void Main()
{
A a = new A();
a.Foo = 17;
B b = PropertyCopy<B>.CopyFrom(a);
bool success = b.Foo == 17; // success is true;
}
}
Two classes with exactly the same signature, in two different namespaces, are two different classes. You will not be able to implicitly convert between them if they do not explicitly state how they can be converted from one to the other using implicit or explicit operators.
There are some things you may be able to do with serialization. WCF DataContract classes on one side do not have to be the exact same type as the DataContract on the other side; they just have to have the same signature and be decorated identically. If this is true for your two objects, you can use a DataContractSerializer to "convert" the types through their DataContract decoration.
If you have control over the implementation of one class or the other, you can also define an implicit or explicit operator that will define how the other class can be converted to yours. This will probably simply return a new reference of a deep copy of the other object in your type. Because this is the case, I would define it as explicit, to make sure the conversion is only performed when you NEED it (it will be used in cases when you explicitly cast, such as myAppCustomer = (Appointment.CustomerParty)myCustCustomer;).
Even if you don't control either class, you can write an extension method, or a third class, that will perform this conversion.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Initialize class fields in constructor or at declaration?
We are arguing about coding practices. The examples here are a little too simple, but the real deal has several constructors. In order to initialise the simple values (eg dates to their min value) I have moved the code out of the constructors and into the field definitions.
public class ConstructorExample
{
string _string = "John";
}
public class ConstructorExample2
{
string _string;
public ConstructorExample2()
{
_string = "John";
}
}
How should it be done by the book? I tend to be very case by case and so am maybe a little lax about this kind of thing. However i feel that occams razor tells me to move the initialisation out of multiple constructors. Of course, I could always move this shared initialisation into a private method.
The question is essentially ... is initialising fields where they are defined as opposed to the constructor bad in any way?
The argument I am facing is one of error handling, but i do not feel it is relevant as there are no possible exceptions that won't be picked up at compile time.
Note that all such field declaration-level initialization will be performed once for each constructor-chain, even if the constructor by itself sets the field to something else.
If you chain constructors together, the fields will be initialized in the common, first, constructor that is called.
Look at this example:
using System;
namespace ClassLibrary3
{
public class Class1
{
private string _Name = "Lasse";
public Class1()
{
}
public Class1(int i)
: this()
{
}
public Class1(bool b)
{
_Name = "Test";
}
}
}
This code compiles as this:
using System;
namespace ClassLibrary3
{
public class Class1
{
private string _Name;
public Class1()
{
_Name = "Lasse"
}
public Class1(int i)
: this()
{
// not here, as this() takes care of it
}
public Class1(bool b)
{
_Name = "Lasse"
_Name = "Test";
}
}
}
It's not necessarily bad to initialize values outside of the constructor, and the problem you have here:
string _string;
public ConstructorExample2()
{
_string = "John";
}
Is that if you have multiple constructors you have to remember to either
1. Reinitialize _string in every constructor
2. Separate the logic out into a common method and call that method in every constructor
3. Call the constructor with the logic in it, from the other constructors. (Chain the constructors)
Now this isn't necessarily a problem, but you have to remember to do it. By initializing it outside of the constructor, it's done for you. It's one less thing you need to remember to do.
Microsoft FxCop by default recommends field initializers over using the constructor. This question is also a duplicate of this one and should provide some insight.
With static classes, you'll have to note some subtleties as addressed at this question.
In the above example the assignment of "John" to _string has no logical reliance on any variables and therefore it should be outside of the constructor in the field initializer.
So long as it is not possible to initialize the object in an non-usable state then it doesn't matter.
When the code is compiled both approaches will be the same anyway.
Not sure about C#, but in Java source code they seem to prefer the constructor, example:
public class String{
char[] value;
int offset;
...
public String(){
value = new char[0];
offset = 0;
...
}
}
I think for simple initializations like that it's fine to do it in the declaration. However, I don't understand the error handling argument. Even if there is an exception in the initialization, I think you will find that your normal error handling mechanism will work the same. It will still throw an exception when you call the constructor.
I tend to initialize things in the get accessor, where they are first used. If null then initialize and all that.
I prefer to initialize simple fields like that outside of the constructor.
It shouldn't cause any issues since compilation actually moves those initializations into the constructor at compile-time anyway.
If the initialization of the variable will be the same, no matter what arguments are passed to the constructor, then it doesn't make sense to clutter the constructor method with the unnecessary initialization code. In this case, I initialize in-place.
Inisialing the fields in the constructor is better. This way if/when a different constructor is added you know that all the fields are starting with null/default values and you can initialise them appropriately.
Sorry for asking it again, there are already some questions about this keyword. But all of them tell the purpose of 'this'.
When do you use this keyword
C# when to use this keyword
Use of “this” keyword in formal parameters for static methods in C#
Proper usage of “this.” keyword in C#?
My question is when not to use 'this' keyword .
OR
Is it all right to use this keyword always in situation like the code
class RssReader
{
private XmlTextReader _rssReader;
private XmlDocument _rssDoc;
private XmlNodeList _xn;
protected XmlNodeList Item { get { return _xn; } }
public int Count { get { return _count; } }
public bool FetchFeed(String url)
{
this._rssReader = new XmlTextReader(url);
this._rssDoc = new XmlDocument();
_rssDoc.Load(_rssReader);
_xn = _rssDoc.SelectNodes("/rss/channel/item");
_count = _xn.Count;
return true;
}
}
here i have not used 'this' with "_xn" and "_count" also not with "_rssDoc.Load(_rssReader);" is it fine? Should i use "this" with all occurrences of class variables within the class?
Edit: Is it useless to use 'this' in a class for its own variables?
I always use this. I use the same naming convention for local variables and private fields and it makes the code much easier to read because it becomes obvious if the used identifier is a field or local variable.
Further it prevents the introduction of bugs by adding a new local variable that hides a field.
internal sealed class Foo
{
private Int32 bar = 42;
private void Bar()
{
// Uncommenting the following line will change the
// semantics of the method and probably introduce
// a bug.
//var bar = 123;
Console.WriteLine(bar);
// This statement will not be affected.
Console.WriteLine(this.bar);
}
}
This can be avoided by using different naming conventions for fields and local variables but I really dislike underscore prefixed names. The first character of a word is very important for its readability and an underscore is one of the worst possible choices.
this is almost always optional and does not need to be specified. If you want to be explicit that you are referring to a member, then use this. If you have a naming convention (such as naming all member fields something like _foo), then you really don't need to refer to them like this._foo.
It's a matter of personal taste (no performance penalty), but I find having the explicit this is harder to maintain and adds little value if you have a solid naming convention. Some people will only use this when calling a member method, e.g. this.Foo(_bar) instead of Foo(_bar), but again, I don't personally believe it adds much.
If you're working with existing code, follow the convention there, otherwise, pick whichever makes you the most productive and effective.
My rule of thumb: Never use 'this' when it is redundant. In this case, 'this' is redundant, so I would avoid it. A tool like ReSharper is very good at telling you when this is the case.
I always use this. to make it clear that I am referring to a class member, not a local variable.
I would try to be consistent, so that people don't get confused into thinking that the few you do the other way (apart from the way you normally pick) have some special significance.
If you don't use the _whatever naming convention for fields, then you should use this.whatever consistently because otherwise there will be problems when constructors take a whatever parameter and try to put in a whatever field.
It is fine. Especially since your class doesn't have a base class and the private fields are named appropriately. ReSharper considers this in your case to be redundant.
Should i use "this" with all occurrences of class variables within the class?
In your particular case, NO.
Consider however the following example:
class RssReader
{
private String url;
public bool FetchFeed (String url)
{
new XmlTextReader (url);
// vs.
new XmlTextReader (this.url);
return true;
}
}
Here you'll need to specify this to access the instance variable that has the same name as the method argument.
there is absolutely no reason not to use this. even redundancy is no reason not to use it, at all. You get the benefit of the intellisense box to safely complete your code and saves your time by selecting the right variable with the down-key and not to maul your keyboard all the time.
You may, but don't need to unless it's a method that takes arguments with the same names as your class vars (to distinguish them).
Well, as for me, 'this' looks really redundant when used with names starting with "_". This is absolutely legal in your example though.
Here is how I look at it. When you call a member (be it method, property or field) of a class as such like DoMyThing(); or return Property; within the instance scope, it's not necessary that you're calling an instance member. DoMyThing or Property can be static members too.
public class Abc
{
public static void Static()
{
}
public Xyz Instance;
public void Test() //instance scope
{
var xyz = Instance; //calls instance member
Static(); //calls static member
}
}
For both of them (static and instance) I've not prefixed anything. Actually my choices are:
do not prefix at all as above
public void Test()
{
var xyz = Instance;
Static();
}
prefix for instance members alone
public void Test()
{
var xyz = this.Instance; // prefixes 'this'
Static();
}
prefix for static members alone
public void Test()
{
var xyz = Instance;
Abc.Static(); //prefixes class
}
prefix in both cases
public void Test()
{
var xyz = this.Instance; // prefixes 'this'
Abc.Static(); //prefixes class
}
This answer is not to say one style is better than other. This is just personal preference. Each has its own claim for correctness and readability.
My take:
a. I for one do not like the inconsistent style of 2. and 3.
b. 1. has the advantage of being more readable for me. Prefixing makes it more about definition than intent.
c. 4. is all about correctness. It has the advantage of being extremely consistent, especially considering you would be forced to prefix for both instance and static members at some point anyway. This is even more important to consider when it comes to base keyword where if you dont prefix with base keyword for a base class member, then adding a member with the same name in current derived class will cause it to override the previous call, changing the whole dynamics.
Personally, I would go with 1. And use this or Abc sparingly when I'm forced to. It's more readable for me, a benefit for me that is good enough to compensate for the little inconsistency it might cause.
Whereas your code will work without ‘this’, it explicitly tells that you mean ‘this’ particular instance of the class. Some people find it easier to read, plus it can help avoid mistakes.
Imagine you made a mistake and wrote…
public string Name
{ get; private set; }
public Forest(string name)
{
name = Name; //these are written in the wrong order...
}
It’s an easy mistake to make given that it’s essentially the same word. Unfortunately the compiler will not catch it - it won’t throw an error. As a result your instance will be created but the property will not have its value assigned. On the other hand if you made the same mistake while using ‘this’…
public string Name
{ get; private set; }
public Forest(string name)
{
this.name = Name; //these are still written in the wrong order but with 'this' prefix...
}
the compiler will throw an error telling you that you are attempting to assign value to a non existent property.
My question stems from MVC's SelectList (and previous generations). Basically the class takes in an IEnumerable and uses the members you define as strings.
How does it interface with the object (casting, reflection?)
(probably redundant) How does it lookup the members as a string.
This is one facet of C# that I have been interested in but could never find examples of :(
EDIT:
I ended up using DataBinder.Eval() from System.Web.UI
It still has the overhead of reflection but makes things easier by allowing you to pass the object and a string containing the hierarchy of the member you want. Right now that doesn't really mean much, but this project was designed to take in Linq data, so not having to worry about it down the road makes my life a tad easier.
Thanks everyone for the help.
While I don't know about its implementation for sure, I'd expect it to use reflection.
Basically you call Type.GetProperty or Type.GetMethod to get the relevant member, then ask it for the value of that property for a specific instance (or call the method, etc). Alternatively there's Type.GetMembers, Type.GetMember etc.
If you want to be able to use "Person.Mother.Name" or similar "paths" you have to do that parsing yourself though, as far as I'm aware. (There may be bits of the framework to do it for you, but they're not in the reflection API.)
Here's a short but complete example:
using System;
using System.Reflection;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Test
{
static void Main()
{
Person jon = new Person { Name = "Jon", Age = 33 };
ShowProperty(jon, "Name");
ShowProperty(jon, "Age");
}
static void ShowProperty(object target, string propertyName)
{
// We don't need no stinkin' error handling or validity
// checking (but you do if you want production code)
PropertyInfo property = target.GetType().GetProperty(propertyName);
object value = property.GetValue(target, null);
Console.WriteLine(value);
}
}
Yes, via reflection. Take a look at the Type class and associated methods. A good place to start might be here.
You can always look at MVC's source for examples too.