Find the output of C#.Net programs | const Keyword | Set 1: Enhance the knowledge of C#.Net const Keyword concepts by solving and finding the output of some C#.Net programs.
Question 1:
using System;
namespace Demo
{
class Program
{
const int A = 10;
//Entry point of the program
static void Main(string[] args)
{
int C;
const int B;
B = 20;
C = A + B;
Console.WriteLine(C);
}
}
}
Question 2:
using System;
namespace Demo
{
class Program
{
const int A = 10;
const int B;
Program():B(20)
{
}
//Entry point of the program
static void Main(string[] args)
{
int C;
C = A + B;
Console.WriteLine(C);
}
}
}
Question 3:
using System;
namespace Demo
{
class Program
{
const void Fun()
{
Console.WriteLine("Fun() called");
}
//Entry point of the program
static void Main(string[] args)
{
Program P = new Program();
P.Fun();
}
}
}
Question 4:
using System;
namespace Demo
{
class Program
{
void Fun()
{
Console.WriteLine("Fun() called");
}
//Entry point of the program
static void Main(string[] args)
{
const Program P = null;
Console.WriteLine("Hello World");
}
}
}
Question 5:
using System;
namespace Demo
{
class Program
{
void Fun()
{
Console.WriteLine("Fun() called");
}
//Entry point of the program
static void Main(string[] args)
{
const Program P = new Program();
P.Fun();
}
}
}
Answer 1:
Output:
Explanation:
The above program will generate syntax error because constant B must be initialized at the time of declaration. But we assigned 20 after its declaration.
Answer 2:
Output:
Explanation:
The above program will generate syntax errors because, in the above program, we tried to initialize const data members using the constructor.
Program():B(20) {}
But we did not use the correct way to initialized const data members. The above constructor definition looks like the member initializer list in C++, but it is not supported in C#.
Answer 3:
Output:
Explanation:
The above program will generate syntax errors because we cannot define a constant method in C#, here we defined method Fun() with const keyword, which is not correct.
Answer 4 :
Output:
Explanation:
The above program will print "Hello World" on the console screen. In the above program, we defined method fun() inside the Program class, and we created a const reference of Program class initialized with null and then we print "Hello World" on the console screen.
Answer 5:
Output:
Explanation:
The above program will generate syntax error because a const reference except string can only be initialized with null, but here we created a const reference for Program class, which is not correct.
need an explanation for this answer? contact us directly to get an explanation for this answer