How to add methods and fields to literal objects? - c#

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;
}
}

Related

Is it possible to constrain a generic type parameter to String OR Array

In short: is it possible to define a generic method where the type parameter (T) is constrained to string or int[]? In pseudo-C#, what I want to do is:
public static int MyMethod<T> ( T arg1, T arg2 )
where T : (has an indexer that returns an int) {
// stuff with arg1[i], arg2[j], etc...
}
Note that in C#, due to the built-in string indexer (which returns a char) along with implicit conversion from char to int, the following expression means precisely the same thing whether source is a string or an int[]:
int someval = source[index];
Per the thread Constrain generic extension method to base types and string I realize I can't just make a list of unassociated types in the where T : x... constraint clause. Both int[] and string would comply with T: IEnumerable<int>, but IEnumerable<T> does not require implementers to have an indexer, which is exactly the common feature I am using from both types.
The purpose behind this is that I'm building some highly optimized string parsing and analyzing functions such as a fast implementation of the Damerau–Levenshtein distance algorithm. I've found that first converting my strings to arrays of int can sometimes yield significantly faster executions in repetitive character-by-character processing (as with the D-L algorithm). This is largely due to the fact that comparing int values is much faster that comparing char values.
The operative word is 'sometimes'. Sometimes it's faster to operate directly on the strings and avoid the cost of first converting and copying to arrays of int. So I now have methods that are truly identical except for the declarations.
Of course I can use dynamic, but the performance penalty from runtime checking completely destroys any gains made in the construction of the methods. (I did test it).
You cannot have a constraint that says “the type must have an indexer”.
However, you can have a constraint that says “the type must implement an interface that has an indexer”. Such an interface might be IList<char>, for example.
Unfortunately, string doesn’t implement IList<char>, so you would have to write a small wrapper class for it:
sealed class StringWrapper : IList<char>
{
public string String { get; private set; }
public StringWrapper(string str) { String = str; }
public static implicit operator StringWrapper(string str)
{
return new StringWrapper(str);
}
public char this[int index]
{
get { return String[index]; }
set { throw new NotSupportedException(); }
}
// Etc.... need to implement all the IList<char> methods
// (just throw NotSupportedException except in the ones that are trivial)
}
And then you can declare your method like this:
public static TElement MyMethod<TCollection, TElement>(TCollection arg)
where TCollection : IList<TElement>
{
return arg[0];
}
[...]
MyMethod<StringWrapper, char>("abc") // returns 'a'
MyMethod<int[], int>(new[] { 1, 2, 3 }) // returns 1
No, C# does not allow you to create a "composite" constraint like that.
The expression you show does mean the same thing, but you can't use that fact to your advantage. C# generics resemble C++ templates syntactically, but they work completely differently, so the fact that the indexer does the same thing ends up being irrelevant.
You could, of course, just create the two overloads with the specific types you need, but that does mean some annoying copy & paste. Any attempts at abstracting this to avoid repetition will cost you performance badly.
You could make your method signature
public static int MyMethod<T> ( T[] arg1, T[] arg2 )
and use String.ToCharArray() before passing string arguments (or maybe in an overload, you get the idea...)

Are parentheses mandatory to include in C# methods?

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

Is it possible define an extension operator method?

is it possible to define an extension method that at the same time is an operator?
I want for a fixed class add the possibility to use a known operator that actually can't be applied.
For this particular case i want to do this:
somestring++; //i really know that this string contains a numeric value
And i don't want to spread types conversions for all the code.
I know that i could create wrapper class over an string and define that operator but i want to know if this kind of thing is possible to avoid search-and-replace every string declaration with MySpecialString.
Edited: as most have say string is sealed, so derivation isn't possible, so i modify "derived" to "wrapper", my mistake.
That is not possible in C#, but why not a standard extension method?
public static class StringExtensions {
public static string Increment(this string s) {
....
}
}
I think somestring.Increment() is even more readable, as you're not confusing people who really dont expect to see ++ applied to a string.
A clear example of where this would be useful is to be able to extend the TimeSpan class to include * and / operators.
This is what would ideally work...
public static class TimeSpanHelper
{
public static TimeSpan operator *(TimeSpan span, double factor)
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
}
public static TimeSpan operator *(double factor, TimeSpan span) // * is commutative
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
}
public static TimeSpan operator /(TimeSpan span, double sections)
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds / factor);
}
public static double operator /(TimeSpan span, TimeSpan period)
{
return span.TotalMilliseconds / period.TotalMilliseconds);
}
}
No, it is not possible to do from outside of the class. ++ operator should be defined inside class which is being incremented. You can either create your own class which will be convertible from string and will have ++ overload or you can forget about this idea and use regular methods.
No, you can't have an extension method which is also an operator. Extension methods can only be declared in static classes, which can't have instances and according to the C# spec,
User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. [7.3.2]
Therefore, it is impossible for an extension method to also be an overloaded operator.
Additionally, you can't override System.String since it is a sealed class.
The string class is sealed in C#, so creating a string-derived class actually isn't possible.
That being said, an extension method will of course work just fine (as will a standard static method in a helper class) but it won't be an operator, just ordinarily-named method.
Currently this is not supported because Extension methods are defined in separate static class and static classes cannot have operator overloading definitions.
This is all true, but it would be nice for M$ to add this functionality in the future. Sometimes the framework is just missing things and an extension can help plug the gap (or fix the issue) this can sometimes be operators.
An example. To compare IP Addresses, you must use the Equals method to directly compare (of course parts of the struct could also be compared as could the address bytes individually - but that's another story). However, using the == operator always returns false at the object level (i.e. without converting them to strings etc). How hard is it to put the Equals method call inside the == operator call (that's rhetorical), but we can't do it. This is inconsistant and a place for bugs to creep in (note it does not fail, just always equates to false - whereas Equals does not).
I would argue that you should use a wrapper class, even if you could write an extension operator.
//i really know that this string contains a numeric value
is exactly the sort of situation that type-safety was invented for.
Another way of looking at it is that by writing that operator, you have broken many other functions and operators that work with the string class, since they don't necessarily preserve the property of containing a numeric value. By using a wrapper class, not a derived class, you only re-implement those features of string that make sense for numeric strings.
i was in a very similar situation as you described: i needed to increase the text (containing a numeric value for sure) in a Windows Forms textbox.
I understand your need as you described
somestring++; //i really know that this string contains a numeric value
My soultion is something like that which i believe is close to your description
somestring = (incrementable)somestring + 1
All i needed to do was
creating class called incrementable
defining an explicit operator in it (to aid converting string to incrementable )
defining an implicit operator in it (to aid converting incrementable back to string )
operator for + (plus sign)
Here's how my class looks in complete
public class incrementable
{
public string s; // For storing string value that holds the number
public incrementable(string _s)
{
s = _s;
}
public static explicit operator incrementable(string tmp)
{
return new incrementable(tmp);
}
public static implicit operator string(incrementable tmp)
{
return tmp.s;
}
public static incrementable operator +(incrementable str, int inc) // This will work flawlessly like `somestring = (incrementable)somestring + 1`
=> new incrementable((Convert.ToInt32(str.s) + inc).ToString());
public static incrementable operator ++(incrementable str) // Unfortunately won't work, see below
=> new incrementable((Convert.ToInt32(str.s) + 1).ToString());
}
Unfortunately i just couldn't get managed to improve my class by the usage of unary ++ operator. The reason against of usage of implicit conversion like ((incrementable)somestring)++ is that it is going to result in error saying The operand of an increment or decrement operator must be a variable, property or indexer hence can not be result of that casting.
Anyway, hope this helps!
As shown in the other answers, it cannot be done directly. But what if you need it, say you want to improve StringBuilder like
void Main()
{
var log = (StringBuilder)"Hello ";
log += "World!";
log += "\nThis example shows how to extend StringBuilder";
log.ToString().Dump();
}
how can you achieve this (i.e. use + operator instead of sb.Append(str);) ?
Answer:
In this case, you can't do it directly, but what you can do is:
Run it in DotNetFiddle
void Main()
{
var log = (StrBuilder)"Hello "; // same as: "Hello ".ToStrBuilder();
log += "World!";
log += "\nThis example shows how to extend StringBuilder";
log.ToString().Dump();
}
public static class Extensions
{
public static StrBuilder ToStrBuilder(this string str)
{
return new StrBuilder(str);
}
}
public class StrBuilder
{
private StringBuilder sb;
public StrBuilder()
{
sb = new StringBuilder();
}
public StrBuilder(string strB)
{
sb = new StringBuilder(strB);
}
public static implicit operator StrBuilder(string self)
{
return new StrBuilder(self);
}
public static StrBuilder operator +(StrBuilder sbA, string strB)
{
return sbA.Append(strB);
}
public StrBuilder Append(string strB)
{
sb.Append(strB);
return this;
}
public override string ToString()
{
return sb.ToString();
}
}
Note: You can't inherit from StringBuilder because it is a sealed class, but you can write a class that "boxes" a StringBuilder - which is, what is done here (thanks to IanNorton's answer regarding implicit conversion).

What do you mean by "extension methods" in C#?

Can anyone else explain this, (beginners approach). Thanks..
Extension Methods are just static methods in static classes that behaves like they were defined in other class.
In the first parameter before the type goes the keyword this wich indicates that is an extension method.
Example:
public static class Extensions
{
public static object ExtensionMethodForStrings( this string s, object otherParameter)
{
//....
return //whatever you want to return or not
}
}
This is an extension method on System.String that takes two parameters:
- string s : This is the instance variable
- object otherParameter: You can have as many as you want including none
You can call this method in two ways:
Static way:
string s = "Your string";
object o = new object(); // or whatever you want
object result = Extensions.ExtensionMethodForStrings(s,o);
Extension Method way
string s = "Your string";
object o = new object(); // or whatever you want
object result = s.ExtensionMethodForStrings(o);
In the second case it works as if the type string has an instance method called ExtensionMethodForStrings. Actually for the compiler the are equivalent.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
The C# article on Extension Methods.
An extension method is a static method in a static class whose first parameter is preceded by the keyword this.
The C# compiler has some syntactic sugar that can convert a call of x.Foo(bar) to SomeExtension.Foo(x, bar). This is used extensively by LINQ (Take, Skip, Where, Select, etc.) but you can also write your own extension methods if you wish.
This question includes lots of examples of useful extension methods:
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)
An extension method is a method that behaves (somewhat) like it is a member of a class, but it is not a member of that class. It can be called on members of that class, but has no reference to the internals of the class.
Extension methods are static methods, and must be members of a static class.
public static class StringExtensions
{
public static string HtmlEncode(this string dataString)
{
return HttpServerUtility.HtmlEncode(dataString);
}
}
The keyword "this" prior to the first parameter type identifies this as an extension method, and the class it extends.
It would be used this way:
string foo = "bar";
string myOutput = foo.HtmlEncode();

C# using the "this" keyword in this situation?

I've completed a OOP course assignment where I design and code a Complex Number class. For extra credit, I can do the following:
Add two complex numbers. The function will take one complex number object as a parameter and return a complex number object. When adding two complex numbers, the real part of the calling object is added to the real part of the complex number object passed as a parameter, and the imaginary part of the calling object is added to the imaginary part of the complex number object passed as a parameter.
Subtract two complex numbers. The
function will take one complex
number object as a parameter and
return a complex number object. When
subtracting two complex numbers, the
real part of the complex number
object passed as a parameter is
subtracted from the real part of the
calling object, and the imaginary
part of the complex number object
passed as a parameter is subtracted
from the imaginary part of the
calling object.
I have coded this up, and I used the this keyword to denote the current instance of the class, the code for my add method is below, and my subtract method looks similar:
public ComplexNumber Add(ComplexNumber c)
{
double realPartAdder = c.GetRealPart();
double complexPartAdder = c.GetComplexPart();
double realPartCaller = this.GetRealPart();
double complexPartCaller = this.GetComplexPart();
double finalRealPart = realPartCaller + realPartAdder;
double finalComplexPart = complexPartCaller + complexPartAdder;
ComplexNumber summedComplex = new ComplexNumber(finalRealPart, finalComplexPart);
return summedComplex;
}
My question is: Did I do this correctly and with good style? (using the this keyword)?
The use of the this keyword can be discussed, but it usually boils down to personal taste. In this case, while being redundant from a technical point of view, I personally think it adds clarity, so I would use it as well.
Use of the redundant this. is encouraged by the Microsoft coding standards as embodied in the StyleCop tool.
You can also to overload math operators, just like:
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
Since you're now learning C# and asking about style, I'm going to show you several things that are wrong with the code you posted along with reasons.
Edit: I only responded to this because it looks like you actually working to figure this stuff out. Since that's the type of people I prefer to work with, I'm more critical simply because I hope it helps you get somewhere better as a result. :)
Structure name
ComplexNumber is unnecessarily long. Note that none of Single, Double, Int32, Int64, etc. have Number in the name. This suggests Complex as a more appropriate name.
Complex matches the naming already established in the .NET Framework.
Real and imaginary components
GetRealPart() and GetComplexPart() should be get-only properties instead of methods.
GetComplexPart() is misnamed because it is actually returning the imaginary part.
Since the .NET framework already has a Complex structure, you shouldn't reinvent the naming. Therefore, unless you are in a position to redefine Framework conventions, the properties must be named Real and Imaginary.
Operations
If you look at existing examples like System.Windows.Vector, you see that math operations are implemented by providing a static method and an operator:
public static Point Add(Vector vector, Point point);
public static Point operator+(Vector vector, Point point);
Not surprisingly, this convention carried over to the System.Numerics.Complex structure:
public static Complex Add(Complex left, Complex right);
public static Complex operator +(Complex left, Complex right);
Summary
The result is clean, easy to verify, and behaves as everyone expects. The this keyword doesn't/can't appear because the methods are static.
public static Complex Add(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
public static Complex operator +(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
I use this keyword only for variables and when there's an argument that has the same name as the private variable. i.e.
private String firstname;
public SetName(String firstname)
{
this.firstname = firstname;
}
I would say yes, it looks correct and easy to read. But isn't this something your TA should answer?
double realPartCaller = this.GetRealPart();
Even if you omit this from GetRealPart() it should still be okay. But the use of this makes it quite easy to read and understand when it comes to maintainer.
double realPartCaller = this.GetRealPart(); ==> bit more readable IMHO
double realPartCaller = GetRealPart();
I find myself more and more using the this keyword for both methods and properties on the current instance, as I feel it increases readability and maintainability. this is especially useful if your class also has static methods and/or properties, on which you of course can not use the this keyword, as these are not related to the current instance. By using this, you clearly see the difference.
To bring it even further, you should consider using the class name as a qualifier for static methods and properties, even within the class itself.
Just to add completeness to the answers - there is one case when the this keyword is mandatory. That's when you have a local variable (or a method parameter) that has the same name as a class member. In this case writing it without this will access the local variable and with this will set the class member. To illustrate:
class MyClass
{
public int SomeVariable;
public void SomeMethod()
{
int SomeVariable;
SomeVariable = 4; // This assigns the local variable.
this.SomeVariable = 6; // This assigns the class member.
}
}
A couple things that follow from this:
Always avoid giving local variables the same name as class members (I admit, I don't always follow this myself);
Writing this in front of all member accesses acts like a safeguard. If you write a piece of code without it, and then later introduce a local variable with the same name and type as a class member, your code will still compile just fine, but will do something completely different (and probably wrong).
One instance though where I use the same names for method parameters as for class members is in constructors. I often write it like this:
class MyClass
{
public int VariableA;
public string VariableB;
public MyClass(int VariableA, string VariableB)
{
this.VariableA = VariableA;
this.VariableB = VariableB;
}
}
In my opinion this makes the constructor clearer, because you immediately understand which parameter sets which class member.
Usage of this keyword seems fine.
Though I believe for a class like Complex you should store the real and complex part as int properties and use them in the method, rather than using the methods GetRealPart() and GetComplexPart()
I would do it this way:
class ComplexNumber
{
public int RealPart { get; set; }
public int ComplexPart { get; set; }
public ComplexNumber(int real, int complex)
{
this.RealPart = real;
this.ComplexPart = complex;
}
public ComplexNumber Add(ComplexNumber c)
{
return new ComplexNumber(this.RealPart + c.RealPart, this.ComplexPart + c.ComplexPart);
}
}
The following is a scenario where this MUST be used, otherwise, the parameter and not the class member is considered for both LHS and RHS of the assignment.
public ComplexNumber(int RealPart, int ComplexPart)
{
RealPart = RealPart; // class member will not be assigned value of RealPart
ComplexPart = ComplexPart;
}
If you follow the naming conventions, using this is rearlly neded:
class MyClass
{
public int _variableA;
public string _variableB;
public MyClass(int variableA, string variableB)
{
_variableA = variableA;
_variableB = variableB;
}
}

Categories