Reputation: 2973
I am new to c# . So cant figure out the below mentioned concept .
using System;
namespace vivek
{
class viku
{
public void func1()
{
Console.WriteLine("Base");
}
}
class Behera
{
static void Main(String[] args)
{
viku v;
v.func1();
}
}
}
After compiling its showing the below error
error CS0165: Use of unassigned local variable 'v'
Upvotes: 1
Views: 216
Reputation: 127583
You seem to be a C++ guy, one thing to help you visualize (but it's not exactly true, its just an analogy) is think of classes in C# as always being pointer refrences in C++.
So if we re-wrote your original code to the "equivilant" in C++ (ignore the memory leak, like I said it is just a basic analogy, not a exact truth) it would be:
namespace vivek
{
class viku
{
public:
void func1()
{
Console::WriteLine("Base");
}
}
class Behera
{
static void Main(String[] args)
{
viku* v;
v->func1();
}
}
}
Now (if I assumed correctly that you know C++) it is obvious why your call to v
did not work, it does not point at any instance of the viku
class.
Upvotes: 2
Reputation: 239724
There's no way for you to instruct the compiler to create an object on the stack in C# - you're working in a managed memory environment now, where the managed side of things has rules that decide where objects are created.
What ends up on the stack is purely an implementation detail. Usually, it will be your reference variables and any local value types1, provided that these variables and value types are not being hoisted due to lambdas, and that you're not writing code in an iterator or async method2.
To create any reference type object (class
declares a reference type, struct
or enum
declares a value type), you have to use new
.
1The fact that local value types sometimes end up on the stack is, as I say, an implementation detail. But there's a persistent myth that "value types go on the stack, reference types go in the heap". You shouldn't change your class
to a struct
just to force it to go on the stack (which it won't always be anyway).
2In all of these situations, the compiler actually re-writes the code that you've written, and what look like local variables become, in fact, fields of a new class
that the compiler constructs for holding them.
Upvotes: 5
Reputation: 3568
To create an object, you need to call a contructor
viku v = new viku();
or even shorter
var v = new viku();
You should read this article about constructors
Upvotes: 1
Reputation: 653
I dont have idea about c# syntax but.. i think it might be
viku v=new viku(); v.func1();
Upvotes: 0
Reputation: 148150
You need to instanstiate object of class.
Change
viku v;
To
viku v = new viku();
Upvotes: 2