Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I know there is some posts on that but I didn't find the answer I'm looking for, and its simple.
I know calling a method static or not (instanciation (OOP)).
Example, using static:
using System;
namespace Projet_Test
{
class surfacesCalcul
{
public static int calc_air(int a, int b){
int result = a * b;
return result;
}
}
/*
* ##########################
* ##########################
*/
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine(surfacesCalcul.calc_air(4,5));
}
}
}
You call the class(surfacesCalcul).Method and you can access the Method.
--
Normal, using OOP:
using System;
namespace Projet_Test
{
class surfacesCalcul
{
public int calc_air(int a, int b){
int result = a * b;
return result;
}
}
/*
* ##########################
* ##########################
*/
class MainClass
{
public static void Main (string[] args)
{
surfacesCalcul calculMeThis = new surfacesCalcul();
Console.WriteLine(calculMeThis.calc_air(4,5));
}
}
}
You create an instantiation and then you can access the methods in the class.
--
[My Question]
Which one is the best, I'm just wondering why using static method more than from an instance or the inverse. Is there a real reason or both are good. Is there a best time to use one more than the other?
I'll argue both sides and you can choose.
Consider your first example with a static function:
namespace Projet_Test
{
class surfacesCalcul
{
public static int calc_air(int a, int b){
int result = a * b;
return result;
}
}
/*
* ##########################
* ##########################
*/
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine(surfacesCalcul.calc_air(4,5));
}
}
}
This is fine if you never care about overriding or any kind of inheritance.
Now consider this example:
class surfacesCalcul
{
public virtual int calc_air(int a, int b){
int result = a * b;
return result;
}
}
class surfacesCalcul2 : surfacesCalcul {
public override int calc_air(int a, int b)
{
var g = base.calc_air(a, b);
return g*2;
}
}
/*
* ##########################
* ##########################
*/
class MainClass
{
public static void Main (string[] args)
{
var calculMeThis = new surfacesCalcul2();
Console.WriteLine(calculMeThis.calc_air(4,5));
}
}
You're not changing the "correctness" of the program at all just allowing polymorphism to do its thing.
This example it really to trivial for it to really matter. I would prefer the route with the class since static methods can't have instance variables and you can't do any kind of dependency injection, which makes unit testing so much easier. The object instantiation also allows for different instances to contain different state information where static can't contain any instance specific data.
Related
This question already has answers here:
Is the order of static class initialization in C# deterministic?
(4 answers)
Closed 1 year ago.
I am totally confused by some of the active discussions on declaration order of types or members in C#.
There is a trending question, what would be the output of this and why?
Scenario 1:
class Program
{
static readonly int A = Method();
static readonly int B = 42;
static int Method() => B;
static void Main()
{
Console.WriteLine(A); // 0
}
}
and if suppose, I update the above code and make it something like this:
Scenario 2:
class Program
{
static readonly int B = 42;
static int Method() => B;
static readonly int A = Method();
static void Main()
{
Console.WriteLine(A); // 42
}
}
The output of Scenario 1 is 0 against the output of Scenario 2 is 42. How this output is zero or 42?
I have checked few answers but aren't able to understand, how and why these answers are 0 and 42.
link 1 link 2
When you write this:
class Program
{
static readonly int A = Method();
static readonly int B = 42;
static int Method() => B;
static void Main()
{
Console.WriteLine(A); // 0
}
}
The compiler will generate a static constructor for you, which assigns the initial values to your various fields. The order of these assignments matches the order that the fields are declared in:
class Program
{
static readonly int A;
static readonly int B;
static Program()
{
A = Method();
B = 42;
}
static int Method() => B;
static void Main()
{
Console.WriteLine(A); // 0
}
}
When the static constructor runs, it's fairly clear that Method() is executed, and A assigned to, before B is assigned to. Fields have an initial value of 0, before anything is assigned to them. So Method() will return 0.
Follow the same logic for your second scenario, and you'll see how it's different.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am getting this error:
"The variable 'a' is assigned but its value is never available"
namespace test
{
public class Program
{
static void Main(string[] args)
{
test();
Console.WriteLine(a);
Console.ReadLine();
}
public static void test()
{
int a = 11;
}
}
}
You are talking about "methods" not classes.
You can read more here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods
But in the mean time, try this:
namespace test
{
public class Program
{
static void Main(string[] args)
{
int a = test();
Console.WriteLine(a);
Console.ReadLine();
}
public static int test()
{
int a = 11;
return a;
}
}
}
class Program
{
static void Main(string[] args)
{
int a = test();
Console.WriteLine(a);
Console.ReadLine();
}
public static int test()
{
int a = 11;
return a;
}
}
You should probably get this error from your code. "The name 'a' does not exist in the current context"
As you do not get the variable "a" out from your method and try to access it.
Try the above and see if it helps.
This is a class and a method, what you have there. NOT 2 classes.
What do you want to do exactly?
The a variable does not exist where you want to print it.
Something like this?
static void Main(string[] args)
{
test();
Console.ReadLine();
}
public static void test()
{
int a = 11;
Console.WriteLine(a);
}
Here, I wish to gain a delegate like function pointer, to point to a class method that's in another class (named Inner), and then pass it to a static function, like below:
public class Inner
{
public int M = 3;
public void F() { Console.WriteLine("f"); }
public void G() { Console.WriteLine("g"); }
}
class Program
{
public static void Caller(Action a)
{
a();
}
static void Main(string[] args)
{
var i = new Inner();
var f = i.F;
var g = i.G;
f();//error
g();//error
Program.Caller(f);
Console.WriteLine("Hello World!");
}
}
I'm from c/c++, and in c/c++, function pointer like this is very straight forward, but this C# code fail to compile. I googled and found almost all delegate explanations talks about delegate that points to class method inside itself.
My question is, how to fix the code to make it work?
Coding Seb's answer highlight's the cause of the issue, but doesn't really explain why.
It is because i.F is a method group, and not a specific method pointer. For example, imagine Inner was defined as so:
public class Inner
{
public void F() { Console.WriteLine("f"); }
public void F(string name) { Console.WriteLine(name); }
}
Which method would i.F refer to? F() or F(string)?
For that reason, you need to define the variable type explicitly, or cast the pointer:
Action f = i.F;
Or:
var f = (Action)i.F;
You can not set methods group in implicit variables in C# so if you just change 2 var in Action it's working
public class Inner
{
public int M = 3;
public void F() { Console.WriteLine("f"); }
public void G() { Console.WriteLine("g"); }
}
class Program
{
public static void Caller(Action a)
{
a();
}
static void Main(string[] args)
{
var i = new Inner();
Action f = i.F;
Action g = i.G;
f();
g();
Program.Caller(f);
Console.WriteLine("Hello World!");
}
}
using System;
namespace _1._75_Using_a_delegate
{
public class Program
{
public delegate int Calculate(int x, int y);
public int Add(int x, int y) { return x + y; }
public int Multiply(int x, int y) { return x * y; }
public void UseDelegate()
{
Calculate calc = Add;
Console.WriteLine(calc(3, 4)); //Displays 7
calc = Multiply;
Console.WriteLine(calc(3, 4));//Displays 12
}
public static void Main()
{
//call and execute UseDelegate()
}
}
}
This should output the above results of 7 and 12.
The delegate function is not directly callable from main in the current state.
Why can't the delegate be seen from main?
Is it necessary to create a class?
How should the delegate function be called?
You cannot call the non-static method from static Method so you have to implement another class like
internal class Check
{
public delegate int Calculate(int x, int y);
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
public void UseDelegate()
{
Calculate calc = Add;
Console.WriteLine(calc(3, 4)); //Displays 7
calc = Multiply;
Console.WriteLine(calc(3, 4));//Displays 12
}
}
your call it from your Main Method like
private static void Main(string[] args)
{
new Check().UseDelegate();
}
You don't call the method at all, and you can't now since the Main method is static and your methods are not.
I would recommend to split your code off to a second class, which is easier to call. (Instead of making all methods static)
public class Assignment
{ /* all code except the Main method goes here */ }
Then, in your Main method, instantiate an instance of the Assignment class and call UseDelegate:
public static void Main()
{
Assignment a = new Assignment();
a.UseDelegate();
Console.ReadKey(); // to prevent the console from closing immediate
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to develop a class library in C# whose methods I would call in a hierarchical way, like this:
using MyProduct.Common;
protected void Page_Load(object sender, EventArgs e)
{
Utils myUtils = new Utils();
int res = myUtils.Numbers.Add(1, 2);
string text = myUtils.Text.ToUpper("test"); //***
}
Is it possible to do, using Namespaces, classes, interfaces, whatever?
UPDATE:
I have my library like this, but it doesn't work, as I can't "reference a type through an expression" (line with *** above)
namespace MyProduct.Common
{
public class Utils
{
public static class Text
{
public static string ToUpper(string s)
{
return s.ToUpper();
}
}
}
}
UPDATE 2:
Ok, it seems I need to clarify...
I have this MyProduct.Common.dll:
namespace MyProduct.Common
{
public static class Utils
{
public static class Text
{
public static void ToUpper(string s)
{
return s.ToUpper();
}
}
public static class Number
{
public static void Add(int a, int b)
{
return (a + b);
}
}
}
}
and I have my project:
using MAD.Comum;
...
protected void Page_Load(object sender, EventArgs e)
{
string x = Utils.Text.ToUpper("aa"); //this works
string res = Utils.Number.Add(1, 2); //this works
}
and now 2 questions:
- is it possible to separate classes Number and Text in 2 files?
- is this a good design?
Of course, you can do something like this:
namespace MyProduct.Common.Utils
{
public static class Numbers
{
public static int Add(int n, int m)
{
return n + m;
}
}
public static class Text
{
public static string ToUpper(string str)
{
return str.ToUpper();
}
}
}
And you use it like this:
MyProduct.Common.Utils.Numbers.Add(1, 2);
Hope this helps.
Cheers