I'm just starting out and I have a question. How do I call a public void?
e.g.
int x, y = 2;
namespace Blah
{
public class blah blah
{
public void count
{
Console.WriteLine("Hi: " + y);
}
public void counting
{
z = x * y
}
}
}
P.S: I have tried this How do I call a non-static method from a static method in C#? and it doesn't work for me
If it's a non-static class, you need to instantiate it first.
Then to call its void methods, justCallThem().
public class blahblah
{
int x, y = 2; // this sets y as 2, but x is not set
public void count()
{
Console.WriteLine("Hi: " + y);
}
public void counting()
{
int z = x * y;
Console.WriteLine("Z = {0}", z);
}
}
class Program
{
static void Main(string[] args)
{
blahblah b = new blahblah(); //instantiate the object
b.count(); //call a method on the object
b.counting();
Console.ReadKey();
}
}
// output:
// Hi: 2
// z = 0
You just need to call the method by the class object reference.
// Blah is a namespace
namespace Blah
{
// blah is the class name
public class blah
{
// x, y and z are member variables.
int x, y = 2;
int z = 0;
// SayHiis a public static method. Thus it dont requires the 'blah' object to call this method.
public static void SayHi()
{
Console.WriteLine("Hi: " + y);
}
// counting is a public non static method. Thus it requires the 'blah' object to call this method.
public void counting()
{
z = x * y;
}
}
}
// CallingMethod is the method where you want to call the counting method of class 'blah'
public void CallingMethod()
{
// As said above, you need a object to call the 'counting' method.
blah objBlah = new blah();
// Now call the non static method using this object.
objBlah.counting();
// and here you can directly call the non-static method SayHi like,
blah.SayHi();
}
Related
Thanks to the kind folks who answered my previous question from a few days ago, I now know how to pass arguments by reference:
static void Main()
{
int i = 0;
Add(ref i, 100);
// now i == 100
}
static void Add(ref int arg, int increment)
{
arg += increment;
}
But is there a way for me not to just pass i by reference, but actually store its location in another variable? By that I mean use i like I did in my example; affecting the original instance, but in a way that's permanently linked and not leaving scope.
I vaguely know that I could use a pointer to determine the location in unsafe context but I was wondering if I could do this without any of that, or if it is just recommended to use the unsafe method.
If you are using C# 7 you can use ref local and ref return to store an updateable reference to any field.
In this example I change the private field _privateField from 0 to 100 from outside Foo, the class in which it is defined, by returning it as a ref int and updating it by reference.
class Foo
{
private int _privateField = 0;
public ref int GetReference()
{
return ref _privateField;
}
public override string ToString()
{
return _privateField.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField = 100;
Console.WriteLine(foo);
}
}
Prior to that, you'd have to store the value in a field contained in an object, and pass around a reference to the object instead.
In this example I change the value from 0 to 100 from outside Foo, even though it is stored (indirectly) in a field that is private inside the Foo instance.
class ValueTypeReference<T> where T : struct
{
public T Value { get; set; }
}
class Foo
{
private ValueTypeReference<int> _privateField = new ValueTypeReference<int>{ Value = 0 };
public ValueTypeReference<int> GetReference()
{
return _privateField;
}
public override string ToString()
{
return _privateField.Value.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField.Value = 100;
Console.WriteLine(foo);
}
}
Output:
100
Well, if I udnerstood you correctly, you want the variable to have global scope, which can be achieved by putting variable as class field/property:
class Program
{
private static int _i;
static void Main()
{
_i = 0;
Add(100);
// now _i == 100
}
static void Add(int increment)
{
_i += 100;
}
}
I'm trying to make a class object and pass the info in the object to the method in program class then call the method in the main method. When I run the program, it doesn't show the values that I pass in the parameters./
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(CreateVsquare(4,7));
}
public static Vsquare CreateVsquare(int width, int length)
{
Vsquare rect = new Vsquare(4,7);
rect.length = length;
rect.width = width;
return rect;
}
}
public class Vsquare
{
public int length;
public int width;
public Vsquare(int w, int l)
{
l = length;
w = width;
}
}
}
Console.WriteLine(object) converts the object parameter to a string by calling the object.ToString() method on the object. By default, object.ToString() returns a string with the name of the object's type; you can override this behavior since the method is virtual, e.g.:
public class Vsquare
{
public int length;
public int width;
public Vsquare(int w, int l)
{
l = length;
w = width;
}
public override string ToString()
{
return $"{l},{w}";
}
}
(As noted in the comments for the question, the constructor's assignment statements are backward, but I haven't fixed that in this excerpt.)
I have a method with this signature:
public static void foo(int x, int y)
{
//do something...
}
I want to verify that this method was called exactly 2 times when x = 5 and y = 10. How can I do that using Typemock?
I gave this a go and came up with the following:
Given the class:
public class Bar
{
public static void Foo(int x, int y)
{
//do something...
Debug.WriteLine($"Method called with {x} {y}");
}
}
Your test would then look like this:
[TestClass]
public class Test
{
[TestMethod]
public void TestMethod()
{
var callCount = 0;
Isolate.WhenCalled(() => Bar.Foo(2, 10))
.WithExactArguments()
.DoInstead(context =>
{
callCount++;
context.WillCallOriginal();
});
Bar.Foo(2, 6);
Bar.Foo(2, 10);
Bar.Foo(2, 10);
Assert.AreEqual(2, callCount);
}
}
i have created a class person which is having functions add,sub,mul
and mytest where i am passing my delegate reference
and in static void main i want if
DateTime.Now.Hour<12 it should call add if DateTime.Now.Hour<20 it should call sub.
but i am getting error
'ad1' does not exist in current context
class person
{
public void add(int x,int y)
{
Console.WriteLine(x+y);
}
public void sub(int x,int y)
{
Console.WriteLine(x-y);
}
public void mul(int x,int y)
{
Console.WriteLine(x*y);
}
public void test(mydel ad1)
{
ad1(2, 3);
}
}
class Program
{
static void Main(string[] args)
{
person p = new person();
if(DateTime.Now.Hour<12)
{
mydel ad1 = p.add;
}
else if(DateTime.Now.Hour<20)
{
mydel ad1 = p.sub;
}
p.test(ad1);
}
}
ad1 is declared inside the if block in the Main method and doesn't exists outside the if scope.
I don't think you need this variable at all just call directly from within the if:
static void Main(string[] args)
{
person p = new person();
if(DateTime.Now.Hour<12)
{
p.test(p.add);
}
else if(DateTime.Now.Hour<20)
{
p.test(p.sub);
}
}
This will also ensure that when Hour > 20 nothing will be called, and you won't get a null exception.
If you do however choose to use this variable, define it before the if (and assign it with null) and ensure it's not null before you use it.
class person
{
public void add(int x, int y) => Console.WriteLine(x + y);
public void sub(int x, int y) => Console.WriteLine(x - y);
public void mul(int x, int y) => Console.WriteLine(x * y);
public void test(Action<int, int> ad1) => ad1(2, 3);
}
class Program
{
static void Main(string[] args)
{
person p = new person();
Action<int, int> action = (x, y) => {};
if (DateTime.Now.Hour < 12)
{
action = p.add;
}
else if (DateTime.Now.Hour < 20)
{
action = p.sub;
}
p.test(action);
}
}
I am new to C#. I've tried this with out parameter in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class First
{
public void fun(out int m)
{
m *= 10;
Console.WriteLine("value of m = " + m);
}
}
class Program
{
static void Main(string[] args)
{
First f = new First();
int x = 30;
f.fun(out x);
}
}
but i get some errors like "Use of unassigned out parameter 'm'" and
The out parameter 'm' must be assigned to before control leaves the current method.
So what is the meaning of these errors and why it is compulsory to assign 'm' when i'm already assigned a value to x.
ref means that you are passing a reference to a variable that has been declared and initialized, before calling the method, and that the method can modify the value of that variable.
out means you are passing a reference to a variable that has been declared but not yet initialized, before calling the method, and that the method must initialize or set it's value before returning.
You're getting an error because a variable sent to a method as an out parameter does not have to be initialized before the method call. The following is 100% correct code:
class Program
{
static void Main(string[] args)
{
First f = new First();
int x;
f.fun(out x);
}
}
Looks like you're looking for ref instead of out here:
class First
{
public void fun(ref int m)
{
m *= 10;
Console.WriteLine("value of m = " + m);
}
}
class Program
{
static void Main(string[] args)
{
First f = new First();
int x = 30;
f.fun(ref x);
}
}
out parameters are for when the function wants to pass a value out of itself. What you want here is ref, which is when the function expects it to be passed in, but can change it.
For examples of how both are supposed to be used, read http://www.dotnetperls.com/parameter. It's explained in simple terms, and you should be able to get a good understanding of it.
You should note that in your code, you never access the variable after the function call, therefore ref doesn't actually do anything. Its purpose is to send changes back to the original variable.
As of C# 7.0 the ability to declare a variable right at the point where it is passed as an out argument was introduced.
Before:
public void PrintCoordinates(Point p)
{
int x, y; // have to "predeclare"
p.GetCoordinates(out x, out y);
WriteLine($"({x}, {y})");
}
C# 7.0
public void PrintCoordinates(Point p)
{
p.GetCoordinates(out int x, out int y);
WriteLine($"({x}, {y})");
}
You can even use var key word:
p.GetCoordinates(out var x, out var y);
Be carefull with the scope of out parameter. For example, in the following code, "i" is only used within if-statement:
public void PrintStars(string s)
{
if (int.TryParse(s, out var i)) { WriteLine(new string('*', i)); }
else { WriteLine("Cloudy - no stars tonight!"); }
}
Further information can be found here. This link is not only about out parameter, but all the new features introduced in c# 7.0
public void Ref_Test(ref int x)
{
var y = x; // ok
x = 10;
}
// x is treated as an unitialized variable
public void Out_Test(out int x)
{
var y = x; // not ok (will not compile)
}
public void Out_Test2(out int x)
{
x = 10;
var y = x; // ok because x is initialized in the line above
}