I have seen multiple tutorials that show C# method creation with parentheses containing parameters or simple empty. I have also seen a C# method written with out parentheses.
public int Value {
get{ return _Value; }
set{ _Value = value; }
}
I haven't tested out that code but is this allowed? Is it considered bad form?
That is a Property and not a method. If you create a Method then it requires ().
As in Philip's answer, your example code is actually a Property,
But you perhaps have hit on something that many actually miss and that is that Properties are implemented using one or two methods. They get created for you by the compiler and contain the contents of each of the get and/or set blocks.
So, a property of:
public string Name {
get {
return "Fred";
}
}
Is a nicer way of writing:
public string GetName() {
return "Fred";
}
Parentheses are mandatory when declaring or invoking a method.
As others have said, what you've shown there is a property, which is implemented as one or two methods behind the scenes (one for each of the "getter" and "setter").
However, you will sometimes see method names without parentheses - these are called method groups and are used to construct instances of delegate types.
For example:
public void Foo(string x)
{
...
}
...
Action<string> action = Foo;
Here Action<string> is a delegate type representing a call with a single string parameter and a void return type. This assignment creates an instance of that delegate type which will call the Foo method when it's invoked, e.g.
action("Test");
will call Foo with an argument of "Test".
That is a property, not a method. A method requires parenthesis.
Bad form depends on context, there are a few design considerations to take into account when deciding to use a property or not.
MSDN has a nice list here: http://msdn.microsoft.com/en-us/library/ms229006.aspx
Related
In object-oriented programming, everything is supposed to be an object. Starting from this postula, is it possible to add methods and fields to a literal object, such as a number, a string, a Boolean value or a character?
I noticed that in C#, we can use some methods and fields of the "Integer" class from a mathematical expression:
var a = (2 + 2).ToString();
I imagine that it is more syntactic sugar to access the "Integer" class and a method actually related to the mathematical expression (and / or its value).
But is it possible in C# to define one of the methods and fields to a literal object alone? Such as these examples:
"Hello, world!".print();
var foo = 9.increment();
This would probably be useless, but the language being object-oriented, this should be feasible. If this is not possible in C#, how could we do this with the object-oriented paradigm?
Sure, you can implement an extension method and have the desired syntax (however, Int32 class will not be changed):
public static class IntExtensions {
public static int increment(this int value) {
return value + 1;
}
}
...
// Syntax sugar: the actual call is "int foo = IntExtensions.increment(9);"
var foo = 9.increment();
In the current C# version (7.2) we can't add extension properties, extension events etc. These options can appear in C# 8.0 (Extension everything, https://msdn.microsoft.com/en-us/magazine/mt829270.aspx):
You don't add methods to a given instance of an object, you add methods to a type. Additionally, the language doesn't allow you to define what methods a string (or other type of) literal has, it defines what methods all strings have, of which string literals act just like any non-literal strings, and have exactly the same methods.
Note that (2 + 2) is not an instance of the "Integer" class, it will resolve to an instance of the System.Int32 struct. The difference isn't relevant to this behavior, but it's relevant to lots of others.
"Hello, world!".print();
This string is an instance of the String Class in C# which inherits from the Object class. So you have to create the print() method in the String Class in order to make this work.
You can use extension methods to achieve this, which must be static methods defined in a static class. In you example above, you could do the following:
public static class Extensions
{
public static int increment(this int num)
{
return ++num;
}
}
I have a question wheater or not it is possible (and if it is, how) to access class members from inside a Func<T, TResult> delegate.
For example, I have the following class:
class NinjaTurtle
{
public string Sound { get; set; }
public Func<string, string> DoNinjaMove { get; set; }
}
Now I'd like to do this
NinjaTurtle leonardo = new NinjaTurtle();
leonardo.Sound = "swiishhh!";
leonardo.DoNinjaMove = (move) => {
if(move == "katana slash") return leonardo.Sound;
return "zirp zirp zirp";
}
The problem is, how do I correctly access the property Sound, when I define the callback function? Is it OK to just use the reference to the instance from outside the function? Would this still work when I pass the object to another method, or even when this would be part of a dll, and I would return the object leonardo from a function in the dll? Would it "survive" serialization / deserialization?
(Thanks Vladimir and Lee, the question is now more specific to what I would like to know).
You can use closures. A closure will be an anonymous delegate or lambda expression which may reference variables, methods, properties, events or anything from an outer scope (oops, it's your case!).
leonardo.DoNinjaMove = (move) => {
// THIS IS VALID! IT'S A CLOSURE! You can access leonardo reference within
// the closure!!
if(move == "katana slash") return leonardo.Sound;
return "zirp zirp zirp";
}
Anyway, DoNinjaMove is Func<string, bool>. If you want to return Sound value, it should be refactored to Func<string, string>.
Further details about how closures work and why you can safely use outer scope's references within them can be found on this other Q&A here in StackOverflow:
How do closures work behind the scenes? (C#)
About if using closures would work when working with satellite assemblies and so...
Yes, there's no problem with that. Closures are a very interesting feature that most modern languages own and it's a must-have feature for languages that have incorporated functional programming. Anyway, it's a must-have feature! :)
If you came here from Google specifically wanting to code a Lambda function as a class member declared inside the class body, read on...
I found this post through google, because I was looking for a way to declare the Lambda Func as a member method of the class itself. You can declare a Func inside of a class but you can't directly assign to it in the same line. Example:
public class myClass {
public Func<string,string> DoNinjaMove; //Can't declare method body here.
}
The solution is to assign the Lambda function body inside the Constructor of the class like this:
public class myClass {
public Func<string,string> DoNinjaMove; //Can't declare method body here.
public myClass()
{
DoNinjaMove = (someString) =>
{
//Do something here
return anotherString;
}
}
}
Now DoNinjaMove is a member of myClass and it's body is also declared inside myClass. DoNinjaMove has access to all members of myClass, and you get the ability to pass DoNinjaMove to other classes/objects for them to call it.
I probably wouldn't recommend this design pattern unless you absolutely know what you're doing. In my case, another library I was using demanded I pass it a Lambda function with a specific input and return type, but I needed the function to be a member of my own class where it had access to class data for the sake of elegance and encapsulation. This is the solution I came up with.
This will capture the variable leonardo in a closure and will work but I don't think this is a good design but it is hard to suggest something different without context.
var leonardo = new NinjaTurtle();
leonardo.Sound = "swiishhh!";
leonardo.DoNinjaMove = (move) =>
{
if (move == "katana slash")
{
return leonardo.Sound;
}
else
{
return "zirp zirp zirp";
}
}
You may want to consider using Func<NinjaTurtle, String, String> and pass the turtle in explicitly.
leonardo.DoNinjaMove = (turtle, move) =>
{
if (move == "katana slash")
{
return turtle.Sound;
}
else
{
return "zirp zirp zirp";
}
}
But this does still not look like a convincing design to me.
Got into a tricky situation in using optional parameters in tandem with method overriding and interfaces in C#. I have read this.
Just wanted to add another dimension to the whole picture. There were quite a few code illustrations in that post. I picked up the one involving tags by VS1 and added another dimension to it as it had interfaces as well as inheritance being demonstrated. Though the code posted over there does work and displays the appropriate string as found in the sub class, base class, and interface, the following code does not.
void Main()
{
SubTag subTag = new SubTag();
ITag subTagOfInterfaceType = new SubTag();
BaseTag subTagOfBaseType = new SubTag();
subTag.WriteTag();
subTagOfInterfaceType.WriteTag();
subTagOfBaseType.WriteTag();
}
public interface ITag
{
void WriteTag(string tagName = "ITag");
}
public class BaseTag :ITag
{
public virtual void WriteTag(string tagName = "BaseTag") { Console.WriteLine(tagName); }
}
public class SubTag : BaseTag
{
public override void WriteTag(string tagName = "SubTag") { Console.WriteLine(tagName); }
}
And the output is
SubTag
ITag
BaseTag
So, it appears that the type of reference holding the reference to the inherited/implemented subclass does matter in determining which optional parameter value gets picked up.
Has anyone faced similar issue and found a solution? Or has C# has got some workaround for this in the later releases? (The one I am using is 4.0)
Thanks.
The C# team did not like adding optional arguments to the language, this is a rather good demonstration why.
It helps to understand how they are implemented. The CLR is quite oblivious of the feature, it is implemented by the compiler. If you write a method call with a missing argument then the C# compiler actually generates the code for the method call with an argument, passing the default value. Easy to see with ildasm.exe.
You can see this back in the language rules, the optional value must be a constant expression. Or in other words, a value that can be determined at compile time. You cannot use the new keyword or an expression that uses variables. Required so the compiler can embed the default value in the assembly metadata. It will need it again when it compiles a call to a method with optional arguments that's declared in another assembly.
The friction here is that the compiler cannot figure out which virtual method is actually going to be called at runtime. Dynamic dispatch is a pure runtime feature.
So all it reasonably can go by is the declared type of the object reference. You used all three versions so you get all three default argument values.
I think optional parameters are syntactic sugar only. So they get picked up at compile time. The compiler doesn't know the actual types of the objects, so the optional values are picked up based on the type of the reference.
If you need this behavior, then you can provide two different methods, one with the parameter and one without, then you can implement the parameterless method differently in different implementations. Of course this only works for fixed parameter layouts.
Update: tested and confirmed, given a void x(int z = 8) method, the method call x() is compiled to x(8), so the parameter values are baked in as constants.
A common way to solve this is to have a special "sentinel" value (often null) which the implementing methods recognise and substitute with the desired value.
For your example, it might look something like this:
public interface ITag
{
void WriteTag(string tagName = null);
}
public class BaseTag :ITag
{
public virtual void WriteTag(string tagName = null)
{
if (tagName == null)
tagName = "BaseTag";
Console.WriteLine(tagName);
}
}
public class SubTag : BaseTag
{
public override void WriteTag(string tagName = null)
{
if (tagName == null)
tagName = "SubTag";
Console.WriteLine(tagName);
}
}
Then your test code will output
SubTag
SubTag
SubTag
which I think is what you want?
I have the following method with an overload:
public string GetName(object obj)
{
return obj.ToString();
}
public string GetName(CustomClass cc)
{
return cc.Name + " - " + cc.Description;
}
Now if I call the method with an untyped IEnumerable wich holds CustomClass the GetName(object obj) gets called, to fix this I have modified the method like this:
public string GetName(object obj)
{
if (obj is CustomClass)
return GetName(obj as CustomClass);
return obj.ToString();
}
I think its rather annoying to write 20 IF statements and catch all the other possibilities, is there an easier way to call the correct overload with an untyped IEnumerable enumeration?
Here is the code that calls the GetName(object obj):
IEnumerable rawData = GetData(); //DataBase method that fetches a CustomClass
foreach (var rawDataItem in rawData)
{
Debug.Print(GetName(rawDataItem)); //calls the GetName(object obj) overload
}
Pls dont tell me to override ToString from my CustomClass, help me fix this method calling problem.
Well, you could use dynamic typing. That will basically defer overload resolution until execution time:
foreach (dynamic rawDataItem in rawData)
{
Debug.Print(GetName(rawDataItem));
}
Note that there's potentially a performance cost here - it may well be minimal and insignificant, but it's worth being aware of.
EDIT: To handle the recursion side of things, you'd probably want two different names, e.g. GetName and GetNameImpl where GetName delegates to GetNameImpl which is what all the useful overloads are called. So you'd have:
// Note that dynamic as a parameter type is equivalent to object for callers.
// The dynamic part is only relevant within the method.
public string GetName(dynamic obj)
{
return GetNameImpl(obj);
}
// Fallback when no other overloads match
private string GetNameImpl(object obj)
{
...
}
private string GetNameImpl(IEnumerable obj)
{
// Maybe build up the name by calling GetName on each element?
}
Note that there's a potential problem with this: if you have two overloads for different interfaces and one type implements both interfaces (but there isn't a specific overload for that type itself) then you'll get an exception at execution time.
If you want callers to be able to call the overloads directly, you could just rename the dynamic one to GetNameDynamic and the others to GetName for example (and make them public).
I rarely find that dynamic is a good solution, but it would avoid the code duplication. I would try to step back and find a different design to be honest. You explicitly rejected it in the question, but polymorphism is the preferred way of handling this. You don't need to necessarily override ToString - you could make all of the custom types implement a particular interface, and use that where it's available, for example.
return GetName((dynamic)obj);
will postpone overload resolution till runtime.
Without dynamic typing, the classic OOP solution to supporting double dispatch (where the method called depends on both the concrete type of the object having the method and the concrete type of the passed object) is the visitor pattern.
Try this:
public string GetName(object obj)
{
if (!(obj is IEnumerable<object>))
return GetName(obj as CustomClass);
return obj.ToString();
}
Here is what I'm trying to setup
My class is named Inventory
I have a static function named List_Departments()
I would like to be able to add an additional function to modify the previous
For Example: Inventory.List_Departments().ToHTML() would return an HTML formatted string containing the data from List_Departments()
If possible i'd like to reuse the same code for another function such as List_Categories()
I would really appreciate a nudge in the right direction on this. I just can't seem to find the correct terminology/ search term to pull up the info I need. Thank you very much for your help, and sorry for the somewhat stupid question.
You need to make the List_Departments method return an object that has a ToHtml method.
Depending on what your exactly methods are returning, you might make a class called something like ObjectList, which would have a ToHtml method, and have the ListDepartments and ListCategories return instances of it.
Alternatively, and especially if your methods are returning existing classes such a DataTable, you could make an extension method for that class called ToHtml.
It sounds like what you're referring to is Extension Methods
Basically, your functions List_Departments() and List_Categories are returning some typed object correct? That being, the object returned would have to have a Method created in it's class definition called ToHTML(). If the two functions return the same type of object then, you only need to define it once. If they return two different types, then you will have to define the ToHTML() method on both return types class definitions.
Unless I'm missing something here, these two functions don't require the static modifier.
If the returning types are types that you don't have source code access to, then you can define an extention method for each type that will process the type of object being returned and can display the ToHTML() for it.
You didn't supply much info, but using Extension methods seems a good approach to me.
An example turning an string into an int:
public static class StringMethods {
public static int ToInt(this String subject) {
int result;
int.TryParse(subject, result);
return result;
}
}
Assuming List_Departments returns Department:
public static class DepartmentMethods {
public static string ToHtml(this Department subject) {
// Whatever you want to do.
}
}
If you do have acces to the internals of the type returned by List_Departments, you can also just add ToHtml there.
the search term you're looking for is Method Chaining :-)
http://www.bing.com/search?q=method+chaining
This is something along the lines of what jQuery does. Basically, you make an object that has all of the methods that you want to be able to chain. Then, using the builder pattern, you can chain all the calls together until you call some final "result" method (ToHtml in your case).
public class Inventory
{
private IEnumerable<Departments> departments;
private IEnumerable<Items> items;
public Inventory ListDepartments()
{
// load up departments to a class level field
return this;
}
public Inventory ListItems()
{
// load up items to a class level field
return this;
}
public string ToHtml()
{
// convert whichever enumerable was previously loaded to HTML
return stringBuilder.ToString();
}
}
That lets you do things such as:
inventory.ListDepartments().ToHtml();
The ToHTML() function is a function that acts on the type returned from List_Departments()
For example:
if Inventory.GetProduct(0) returns an int. You can use Inventory.GetProduct(0).ToString() because ToString() is a method of an integer type.
In order to do this, List_Departments() would have to return a custom object that has a method called ToHTML() say
public class Department() {
public HtmlDocument ToHTML() {
//Create the html document to return here
}
}