C# static method [closed] - c#

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 9 years ago.
Improve this question
I have a problem with a example of my book. From what i have read non static methods cant be used without instance a object of the class. So is this ok ?
public partial class TempAgencyForm : Form
{
public TempAgencyForm()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
...
setVisibility(false);
}
private void setVisibility(bool visibilityValue)
{
...
}
}

Yes, it is fine. One non-static method can call another non-static method.
The call:
setVisibility(false);
can also be written:
this.setVisibility(false);
but the this qualifier is redundant.
However, if you had tried to call a non-static method without instance qualification from inside a static member, that would have been a problem (compile-time error).

I assume you are talking about calling setVisibility(false);. Yes it is fine, neither it or the method calling it are static.
This will all happen within an instance of TempAgencyForm

Yes this is okay, because it's called from within another member.
You're correct, since setVisibility() is not static, it always has to be called in the context of some object of the parent class (TempAgencyForm in this example).
However, btnCalculate_Click() is another member of TempAgencyForm, as such you're able to access the current/local object using the this keyword (this.setVisibility()), which is optional if there's no disambiguity.

static or non static doesnt matter here, you are calling a member function declared within the same object. so short answer is "fine"
how you call TempAgencyForm members may be what you are referring to
in this case (as you have defined) instantiations is required
TempAgencyForm taf = new TempAgencyForm()
taf.setVisibility(false);
however if you have your class definition itself as static, i.e.
public static partial class TempAgencyForm
then,
TempAgencyForm.setVisibility(false);
is suffice (without instantiating the object) as the object is already loaded on stack at the time of application start

Related

Using static variables and methods vs. non-static [closed]

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 4 years ago.
Improve this question
I am developing an ASP/c# webform where I am using JQuery as well. I came into a scenario where I need to call. C# function from JQuery. In order to that, I found that function in c# has to be a static method (web method).
The problem is that I need to access all variables, arrays, etc which I used to populat some data and these are not stated c variables. Also, from the web method I need to re-use some the functions which are not static. I ended up gradually just changing all methods and variables to static.
I would like to know if the approach I am taking is correct, and whether there is any pitfall of using static variables/methods and what in simple words makes a difference between static/none-static.
Static variables can be called directly by using class names such as
public class IhaveStatic
{
public static string Hello = "Hello I am A";
}
When you use static this means this will be in memory for life time of your process.
now consider another class as
public class IhaveNoStatic
{
public string Hello = "Hello I am B"
}
public class C
{
Console.WriteLine(IhaveStatic.Hello); // Correct
IhaveNoStatic obj = new IhaveNoStatic();
Console.WriteLine(obj); // Correct
Console.WriteLine(IhaveNoStatic.Hello); // Compile time error
}
as you can see that you need to create object of that class "IhaveNoStatic" to access non-static variable. So, this will be in memory until there is an instance of that class exist.
So, basically it's on your requirement but it is good to use less static variable in your programs.

Should a class with only static methods be static? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a class with only static methods. Should the class itself be made static too? Does it matter?
Does it matter?
Making a class static ensures that it can never be instantiated by generating a compiler error should the user attempt to do so. If the class, consisting of only static members, is simply not intended to be instantiated, there is no reason not to make it static. You can choose not to do so, but instances of such a class aren't going to be very useful, and users creating these instances are going to be left quite confused.
On the other hand, if you intend for instances of this class to be created but you expect derived classes to implement their own instance members, chances are that this class should be abstract, rather than static (and perhaps those instance members should be stated upfront via abstract definitions or an interface).
In general: Yes.
You can prevent the programmer to create object instances of a certain class by making the class static. If this is what you intend, then do it. This prevents mistakes, by showing (other collegues, etc.) that the class is not intended to be instantiated.
public static class A
{
// Some static member
}
A a = new A(); // Compilation error

How can i program this UML class diagram to C# language? [closed]

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 7 years ago.
Improve this question
I am confused on how to create class can you please help me??
class AutomotiveManager
{
private bool isBeingTested
{
set
{
isBeingTested= false;
}
}
private dialogResult MessageBoxResult
{
///need help over here
}
}
It seems that there are a few different issues here.
The difference between properties and attributes
The meaning of the = in the attributes
The error (which error?) you get for the declaration of the messageBoxResult
Private Attributes are just private Attributes.
So the implementation of a private attribute like the isBeingTested would be
private bool isBeingTested;
The = in the attributes means the default value. So that would be the value you assign in the constructor or at the declaration of the attribute. For the isBeingTested you could add that to the declaration like this:
private bool isBeingTested = false;
But since in C# the default value for a boolean is false anyway you don't even need to specify it. The way you programmed it you will en up in an infinite loop the moment you try to use the setter for isBeingTested
The «Property» presumably indicates that you are meant to create a Property rather then an Attribute, and I guess the {get;} indicates that you only need to implement a getter, not a setter for this property. (I'm guessing here since none of that is defined in UML)
The error you are getting is probably because the compiler doesn't know the type dialogResult. It may know the type DialogResult (notice the uppercase) if you add System.Windows.Forms as a reference to your project, and add a using statement like this
using System.Windows.Forms;
PS. You also failed to implement the static keyword on the class.
To convert your UML class diagram into a C# class, you'll need to understand what each of the symbols represent in your UML class diagram. This image from tutorialspoint.com is useful:
From there, it's a matter of writing the equivalent C# code based on the symbols provided in your example.

How to invoke a method that called the current method in c# [closed]

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 7 years ago.
Improve this question
I want to recall a method from the called method, can i use action for that, or any other solution.
I see some ambiguity in your question use case..
Let us take a simple use case: You want to call some one and they in turn call you back. Is there any use to it and when do you want to stop this and go ahead to get some work done?!
For example following code like what you are expecting will go in infinite recursion and result in StackOverflowException
class MyClass
{
public void TargetMethod(Action callback)
{
Console.WriteLine("Inside TargetMethod");
callback(); //This call the SourceMethod() and which inturn call TargetMethod() again in infinite recursion.
}
public void SourceMethod()
{
Console.WriteLine("Inside SourceMethod");
TargetMethod(SourceMethod);
}
}
//Calling code
MyClass objMyClass = new MyClass();
objMyClass.SourceMethod();
Instead you can use Callback mechanism, so that once you done within the target method, notify another handler method that in turn can do some stuff like logging or updating UI etc., case specific stuff.
class MyClass
{
public void TargetMethod(Action callback)
{
Console.WriteLine("Inside TargetMethod");
callback(); //This calls/notify the handler to do some stuff.
}
public void SourceMethod()
{
Console.WriteLine("Inside SourceMethod");
TargetMethod(CallbackHandler); //Notice here we are calling to a handler which can do some stuff for us.
}
public void CallbackHandler()
{
Console.WriteLine("Inside CallbackHandler");
}
}
This code is just for quick demonstration purpose and you can enhance design further in your implementation.
Hope this provide you some heads-up on why you need to revisit your design..
You should not do this in normal situations, your design is probably wrong!
You can use the CallerInfoAttribute to get the caller and use reflection to invoke it.
But... that is a lot of work and I think you are not very skilled. Luckily, there is another way!
You can add a parameter of type MethodInfo. And let's say A() calls B(MethodInfo). Then A needs to get its reflected self and pass it into B. Then in B you can use MethodInfo.Invoke to invoke the method.
Well... it turns out that the alternative requires reflection too... So if you are not familiar with reflection, learn more about it first!
If you want to know more about MethodInfo, go to here: https://msdn.microsoft.com/en-us/library/system.reflection.methodinfo(v=vs.110).aspx

need clarification for Constructors in c# [closed]

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 9 years ago.
Improve this question
I want to know whether my understanding on the constructors is correct or not. I just tried to attempt a quiz for constructors but confused whether my understanding is correct or not
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, the compiler automatically provides a default constructor.)
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.)
--> A static constructor in a non­static class is called once on each object creation. – False (If a static constructor has been called once, compiler will not call it again, it will get called once only .The execution of a static constructor is triggered by the first of the following events to occur within an application domain: 1. An instance of the class type is created. 2. Any of the static members of the class type are referenced.)
-->You can specify on the constructor which classes of interfaces that class is inheriting
( i don't know please clarify )
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, > > the compiler automatically provides a default constructor.)
- Your understanding is Correct
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a
special instance constructor. It is generally used in classes that
contain static members only. If a class has one or more private
constructors and no public constructors, other classes (except nested
classes) cannot create instances of this class.)
- You can have a private constructor, in which case other classes cannot create instance of it (but why will you do that?)- People do that to put some control in object's instantiation, as what they do commonly in some design patterns. In a nutshell, you can still create an instance of a class with private constructor thru some other means (e.g. from static methods).
--> A static constructor in a non­static class is called once on each object creation. – False (If a static constructor has been called
once, compiler will not call it again, it will get called once only
.The execution of a static constructor is triggered by the first of
the following events to occur within an application domain: 1. An
instance of the class type is created. 2. Any of the static members of
the class type are referenced.)
- Your understanding is Correct
-->You can specify on the constructor which classes of interfaces that class is inheriting ( i don't know please clarify )
- False, You specify in the class declaration itself the interfaces or classes that the class is going to inherit not in the constructor

Categories

Resources