0

Opreater overloading method and create a new object in it

namespace SoloLearn { class Program { static void Main(string[] args) { Score tm1 = new Score(2, 3); Score tm2 = new Score(4, 2); Score finalScores = tm1 + tm2; Console.WriteLine("Round 1: " + finalScores.round1Score); Console.WriteLine("Round 2: " + finalScores.round2Score); } } class Score { public int round1Score { get; set; } public int round2Score { get; set; } public Score(int r1, int r2) { round1Score = r1; round2Score = r2; } public static Score operator+(Score a, Score b) { int h = a.round1Score + b.round1Score ; int w = a.round2Score + b.round2Score ; Score res = new Score (h, w); return res; } } } Why in this method (Score operator +) although it is defined static, but a new instance is created in it ( Score res = new Score (h, w);). We know that when a method is defined statical there is no need to create a new object

17th Oct 2023, 4:12 AM
safir safir1
safir safir1 - avatar
2 Antworten
+ 1
A static method is a method where you dont need a instance to call it, but it is still allowed to have a return value (including instantiated objects), meanwhile in a static class you cant instantiate the class, since your class is not static it can be instantiated
18th Oct 2023, 11:54 PM
Nest Admiral
Nest Admiral - avatar
+ 2
static simply means that a method / member belongs to the Class and not the instance. You are still returning a Score hence return res
17th Oct 2023, 6:01 AM
Raul Ramirez
Raul Ramirez - avatar