This is my code. I am not able to figure out why this code is giving 'Process is Terminated due to StackOverFlowException'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SadiSDAL4
{
class Program
{
static void Main(string[] args)
{
PrivateVehical privateV = new PrivateVehical("001");
PrivateVehical pVehical = (PrivateVehical)privateV.Clone();
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
privateV.name = "Sadia's Car";
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
pVehical.name = "Waheed's Car";
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
Console.WriteLine(privateV.GetHashCode().ToString());
Console.WriteLine(pVehical.GetHashCode().ToString());
PublicVehical publicV = new PublicVehical("002");
Console.WriteLine(publicV.id);
PublicVehical pubVehi = (PublicVehical)publicV.Clone();
Console.WriteLine("Cloned : {0}", pubVehi.id);
}
}
abstract class Vehical
{
private string vehicalId = "01";
public string name = "Car_1";
public Vehical(string id)
{
this.vehicalId = id;
}
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
public abstract Vehical Clone();
}
class PrivateVehical : Vehical
{
public PrivateVehical(string id)
: base(id)
{
}
public override Vehical Clone()
{
return (Vehical)this.MemberwiseClone();
}
}
class PublicVehical : Vehical
{
public PublicVehical(string id)
: base(id)
{
}
public override Vehical Clone()
{
return (Vehical)this.MemberwiseClone();
}
}
}
This is the output. Can someone explain what is the cause of it ? Why it is working in first part & not in the other ?
StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. So make sure your code doesn't have an infinite loop or infinite recursion.
A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }
Take a look at this code:
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
Specifically get { return id; }
. You are returning property to itself, causing SO error.
Is this what you intended:
public string id
{
get { return this.vehicalId; }
set { this.vehicalId = value; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With