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;
}
}
Related
I was looking for a way to calculate the addition of complex numbers and I saw this example but there is a part which I don't understand. this is the whole code for this class:
class Complex
{
public int real, imaginary;
public Complex()
{
}
public Complex(int tempReal , int tempImaginary)
{
real = tempReal;
imaginary = tempImaginary;
}
public Complex addComp(Complex C1 , Complex C2)
{
Complex temp = new Complex();
temp.real = C1.real + C2.real;
temp.imaginary = C1.imaginary + C2.imaginary;
return temp;
}
}
The part where it is written :
public Complex addComp(Complex C1 , Complex C2)
My question is first is this a constructor or method? and my next question is why is Complex written behind addComp? how is that possible and what is the point of it?
addComp is a method, but a very badly written one!
Observations:
addComp should either be static and take two parameters, or be non-static and take one; an instance method shouldn't ignore the this value, most times
addComp should almost certainly be the binary + operator, which would be static in the above scenario (C# allows you to overload many operators, including +)
Complex should probably be a readonly struct, not a class - with suitable operators and overloads, support for IEquatable<Complex>, etc
real and imaginary should be properties, not public fields
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;
}
}
This is an attempt to learn Generics (with .Net 4.0). I have been programming for about 4.5 years. Till now I have not used Generics in real time projects. All the time what I have been doing is reading some article about generics and try to understand it. The problem is – most of them try to explains various syntax available with Generics. They explain with examples such as Square, Circle and shapes.
Now I have got a chance to design a small application. I would like to use Generics there. [I do see good chances of Generics being a good candidate in my new project]
What I have come up with now is an example from Bank domain with the intention of understanding Generics. I am trying to understand the following 4.
1) Generic classes
2) Generic Methods
3) Generic Interfaces
4) Generic Delegates
EDIT: Operations that are type-independant are good candidates for generics. This is the one of the biggest points I missed in my following example.
I have created an example for “Generic classes”. Could you please help with simple examples for other three items with the Bank domain?
Note: While using Generic class, I came to know that it helped in Open-Closed Principle. Even if I add new account type, the generic class need to change. The changing logic (interest calculation) goes inside the specific class.
Note: In the following, the syntax may not be correct as it typed it without a Visual Studio. But the concept holds good.
EDIT: Will "AccountManager" be a more better name for "BankAccount" class based on its role? Is it any kind of anti-pattern?
Generic Class - Example with Bank Domain
Public Interface IBankAccount
{
Public int Interest;
Public Int DepositedAmount;
Public int DurationInMonth;
}
Public class FixedAccount: IbankAccount
{
Public int Interest
{
Get
{
Return (DurationInMonth*0.5)
}
}
Public Int DepositedAmount {get;set};
Public int DurationInMonth {get;set};
}
Public class SavingsAccount: IbankAccount
{
Public int Interest
{
Get
{
Return ((DurationInMonth/2)*0.1)
}
}
Public Int DepositedAmount {get;set};
Public int DurationInMonth {get;set};
}
Public Class BankAccount<T> Where T: IbankAccount
{
T account = new T();
Public void CreateAccount(int duration, int amount)
{
account. DurationInMonth = duration;
account. DepositedAmount = amont;
int interestVal = account. Interest;
SaveToDatabase (T);
}
}
READING:
When is it Appropriate to use Generics Versus Inheritance?
Generics vs inheritance (when no collection classes are involved)
https://codereview.stackexchange.com/questions/8797/how-to-make-sure-that-this-code-conforms-to-open-close-principle
A Factory Pattern that will satisfy the Open/Closed Principle?
I'm having some trouble with generics and casting in C#
Deciding When and Where to Use Generics
http://en.csharp-online.net/CSharp_Generics_Recipes—Deciding_When_and_Where_to_Use_Generics_Problem
Code reuse through generics vs polymorphism
Polymorphism AND type safety in parallel inheritance chains
Extending using C# generics?
C# Generics and polymorphism: an oxymoron?
Shoe-horning generics into a project just because "I want to use generics" is usually a bad idea. use the right tool for the right job. now, props for trying to learn something new.
that said...
Basically, a "generic" is a way of specifying a method, class (etc) without specifying an underlying type when you write it. It is a good way to separate your algorithm from you data type.
take, for example, a Swap method. Basically, the swap algorithm is the same no matter what the type it is operating on. So, this would be a good candidate for a generic (as would a List, a Dictionary, etc)
so, a swap for an int would like like this:
void Swap(ref int left, ref int right)
{
int temp = left;
left = right;
right = temp;
}
now, you COULD write overloads for your other datatypes (float, double, etc)
or you COULD make it a generic and write it once so it will work on pretty much all datatypes:
void Swap<_type>(ref _type left, ref _type right)
{
_type temp = left;
left = right;
right = temp;
}
now, your sample code wont work:
Public void CreateAccount(int duration, int amount)
{
T.DurationInMonth = duration;
T.DepositedAmount = amont;
int interestVal = T.Interest;
SaveToDatabase (T);
}
here, T is the type, not an instance of an object. if you substitute for T, it becomes clearer what is going on:
Public void CreateAccount(int duration, int amount)
{
IbankAccount.DurationInMonth = duration;
IbankAccount.DepositedAmount = amont;
int interestVal = IbankAccount.Interest;
SaveToDatabase (IbankAccount);
}
when what you REALLY want is this:
Public void CreateAccount(int duration, int amount)
{
account.DurationInMonth = duration;
account.DepositedAmount = amont;
int interestVal = account.Interest;
SaveToDatabase (account);
}
you see, here we are calling the methods of the INSTANCE of the class account, not of the generic IbankAccount TYPE
Just my two cents, since #Lijo asked me to comment here.
I would go with most of the above answers.
But to summarise, Generics is typeless reuse of behaviour. The fact that your generic type has to be an IBankAccount -which is a very specific interface - is saying this probably is not right. I am not saying that you cannot use restrictions for an interface but that interface would be a very generic interface itself such as IDisposable or IConvertible.
Generics are about generic type parameters. If you want to program something and you do not know for which type it will be applied in advance, you would declare a generic type parameter.
class MyStore<T>
{
}
Here T is a generic type parameter. You do not know for which type it stands for.
You could write something like this
class MyStore<T>
{
public void Store(T item)
{
...
}
public T Retrieve()
{
...
}
}
Now you can use MyStore like this:
var stringStore = new MyStore<string>();
stringStore.Store("Hello");
string s = stringStore.Retrieve();
var intStore = new MyStore<int>();
intStore.Store(77);
int i = intStore.Retrieve();
You could also declare the store like this; however, it would not be type safe
class MyStore
{
public void Store(object item)
{
...
}
public object Retrieve()
{
...
}
}
You would have to cast the results
var stringStore = new MyStore();
stringStore.Store("Hello");
string s = (string)stringStore.Retrieve();
var intStore = new MyStore();
intStore.Store(77);
int i = (int)intStore.Retrieve();
var doubleStore = new MyStore();
doubleStore.Store("double");
double d = (double)doubleStore.Retrieve(); // OOPS! A runtime error is generated here!
0) Using .NET's generic collections with your types as container types: Suppose you want to list all the accounts associated with a specific customer, and display them in a data grid. A List<IBankAccount> would be helpful, or a Dictionary<ICustomerID,IBankAccount> if you wanted to look at more than one customer's account.
1,2) Creating your own generic class and generic methods: Say you want to perform a calculation which involves all accounts in order to generate a report. In this particular report, numerical precision is not important, and speed is. So you could use Single insted of Decimal. In this particular case, to make the classes involved in the calculation independent of the numeric type used, using a generic argument is more natural than inheritance. Pseudo code:
public class MetricCalculator<T>{
private bool _dirty;
private T _cachedValue;
T PerformCalculation(){
if( !_dirty )
return cachedValue;
T metric = 0;
foreach( IBankAccount account in AccountMapper.GetAll() ){
T += account.Foo * accound.Bar;
}
_cachedValue = metric;
return metric;
}
}
In this example, MetricCalculator is a generic class because one of its data members is of the parameterized type. That member is used to avoid repeating the calculation if the values used haven't changed. There is also a generic method, which performs calculations without caring about the numeric type used. If there were no need to cache the value, you could have just a common class with a generic method. I combined both just to save space.
3) Generic interface: Suppose you want to completely decouple all your components (to implement Inversion of Control, for example) ; in that case, if you had generic classes like MetricCalculator that were used across assemblies, you'd need to use them via a generic interface. Another example would be if you needed to write a custom data structure or iterator, but I doubt you'd have to come to that.
4) Generic events: Back to the MetricCalculator example, suppose that you want to notify some observer object with an event that notifies that the calculation is done, and pass the result. It would be like an usual event, but you'd pass an argument of type T when raising the event. Note: it might be better to use C#5's async-await feature if available.
I've got somebody's F# library with a type in it:
module HisModule
type hisType {
a : float;
b : float;
c : float;
}
I'm using it in C#, and I would like to add a "ToString()" method to it, in order to facilitate debugging.
But the following doesn't seem to work:
public static class MyExtensions
{
public static string ToString(this HisModule.hisType h)
{
return String.Format("a={0},b={1},c={2}", h.a, h.b, h.c);
}
}
....
var h = new hisType();
Console.WriteLine(h.ToString()); // prints "HisModule+hisType"
Any ideas why not?
As others have pointed out, the ToString on object will always be a better match than your extension method. You should probably change the signature of your extension method; changing the name is probably the right way to go.
Moreover: you said that the purpose of this thing was to facilitate debugging. Overriding ToString might be the wrong thing to do there; ToString might be used for something other than debugging. I would be inclined to make my own specially-named method whose name clearly reflects the purpose of the method.
If you are creating a new type and want to have special display behaviour in the debugger, the easiest thing to do is to use the Debugger Display Attributes.
If you want to get really fancy to display a complex data structure in an interesting way, consider writing a Debugger Visualizer.
The answer to your question is "yes". Your sample does not succeed, however, because method resolution succeeds when it finds object.ToString(), so the compiler never looks for extension methods. Try it with a different name:
public static class MyExtensions
{
public static string Foo(this HisModule.hisType h)
{
return String.Format("a={0},b={1},c={2}", h.a, h.b, h.c);
}
}
....
var h = new hisType();
Console.WriteLine(h.Foo());
I think you can not do that, as ToString() is always there, in any object of CLR world.
Check out Eric Lippert answer.
You could create a wrapper type (with an implicit conversion) that overrides ToString.
class MyType {
private readonly hisType _hisType;
private MyType(hisType hisType) {
_hisType = hisType;
}
public static implicit operator MyType(hisType hisType) {
return new MyType(hisType);
}
public override string ToString() {
return String.Format("a={0},b={1},c={2}", _hisType.a, _hisType.b, _hisType.c);
}
}
hisType y;
MyType x = y;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# generic constraint for only integers
Greets!
I'm attempting to set up a Cartesian coordinate system in C#, but I don't want to restrict myself to any one numerical type for my coordinate values. Sometimes they could be integers, and other times they could be rational numbers, depending on context.
This screams "generic class" to me, but I'm stumped as to how to constrict the type to both integrals and floating points. I can't seem to find a class that covers any concept of real numbers...
public class Point<T> where T : [SomeClassThatIncludesBothIntsandFloats?] {
T myX, myY;
public Point(T x, T y) {
myX = x;
myY = y;
}
}
Point<int> pInt = new Point<int>(5, -10);
Point<float> pFloat = new Point<float>(3.14159, -0.2357);
If I want this level of freedom, am I electing for a "typeof(T)" nightmare when it comes to calculations inside my classes, weeding out bools, strings, objects, etc? Or worse, am I electing to make a class for each type of number I want to work with, each with the same internal math formulae?
Any help would be appreciated. Thanks!
You can't define such a constraint, but you could check the type at runtime. That won't help you for doing calculations though.
If you want to do calculations, something like this would be an option:
class Calculations<T, S> where S: Calculator<T>, new()
{
Calculator<T> _calculator = new S();
public T Square(T a)
{
return _calculator.Multiply(a, a);
}
}
abstract class Calculator<T>
{
public abstract T Multiply(T a, T b);
}
class IntCalculator : Calculator<int>
{
public override int Multiply(int a, int b)
{
return a * b;
}
}
Likewise, define a FloatCalculator and any operations you need. It's not particularly fast, though faster than the C# 4.0 dynamic construct.
var calc = new Calculations<int, IntCalculator>();
var result = calc.Square(10);
A side-effect is that you will only be able to instantiate Calculator if the type you pass to it has a matching Calculator<T> implementation, so you don't have to do runtime type checking.
This is basically what Hejlsberg was referring to in this interview where the issue is discussed. Personally I would still like to see some kind of base type :)
This is a very common question; if you are using .NET 3.5, there is a lot of support for this in MiscUtil, via the Operator class, which supports inbuilt types and any custom types with operators (including "lifted" operators); in particular, this allows use with generics, for example:
public static T Sum<T>(this IEnumerable<T> source) {
T sum = Operator<T>.Zero;
foreach (T value in source) {
if (value != null) {
sum = Operator.Add(sum, value);
}
}
return sum;
}
Or for another example; Complex<T>
This is a known problem, since none of the arithmetic classes arrive from the same class. So you cannot restrict it.
The only thing you could do is
where T : struct
but thats not exactly what you want.
Here is a link to the specific issue.
Arithmetic types like int,double,decimal should implement IArithmetic<T>
You actually can do this, although the solution is tedious to set up, and can be confusing to devs who are not aware of why it was done. (so if you elect to do it document it thououghly!)...
Create two structs, called say, MyInt, and MyDecimal which act as facades to the CTS Int32, and Decimal core types (They contain an internal field of that respective type.) Each should have a ctor that takes an instance of the Core CTS type as input parameter..
Make each one implement an empty interface called INumeric
Then, in your generic methods, make the constraint based upon this interface.
Downside, everywhere you want to use these methods you have to construct an instance of the appropriate custom type instead of the Core CTS type, and pass the custom type to the method.
NOTE: coding the custom structs to properly emulate all the behavior of the core CTS types is the tedious part... You have to implement several built-in CLR interfaces (IComparable, etc.) and overload all the arithmetic, and boolean operators...
You can get closer with implementing few more
public class Point<T> where T : struct, IComparable, IFormattable, IConvertible,
IComparable<T>, IEquatable<T> {
}
The signature conforms to DateTime too. I'm not sure if you will be able to specify more types from the framework. Anyway this only solves part of the problem. To do basic numeric operations you will have to wrap your numeric types and use generic methods instead of standard operators. See this SO question for a few options.
This might be helpful. You have to use a generic class to achieve what you want.
C# doesn't currently allow type constraints on value types. i asked a related question not too long ago.
Enum type constraints in C#
Would this not lend itself to having seperate classes implementing IPoint?
Something like:
public interface IPoint<T>
{
T X { get; set; }
T Y { get; set; }
}
public class IntegerPoint : IPoint<int>
{
public int X { get; set; }
public int Y { get; set; }
}
As the calculations will have to differ in each implementation anyway right?
Dan#