R
rowe_newsgroups
I was recently asked to explain why the below code set's the property
values in the load method, but the values aren't persisted upon
leaving the load method.
To be honest, I can't think of a great explanation on why it doesn't
work, so I figured I'd post here and see if one of the guru's could
tell me exactly what's happening and why. I'm guessing this has to do
with the fact you need to pass the object by ref, which can't be done
with "this".
Here's a complete console application that demonstrates the behavior:
/////////////////////
using System;
namespace ConsoleApplication1
{
public class Program
{
public static void Main()
{
var fooObject = new FooObject();
fooObject.Load();
Console.WriteLine(fooObject.Name);
Console.WriteLine(fooObject.Description);
Console.Read();
}
}
public class FooObject
{
public string Name { get; set; }
public string Description { get; set; }
public void Load()
{
DALC.LoadFooObject(this);
}
}
public static class DALC
{
public static void LoadFooObject(FooObject fooObject)
{
/*
This of course works, but they don't want to do it
(long story)
fooObject.Name = "name";
fooObject.Description = "some
description";
*/
var temp = new FooObject()
{
Name = "name",
Description = "some description"
};
// This is the issue, the property values are set here,
but not
// persisted once we leave the method.
fooObject = temp;
}
}
}
/////////////////////
Thanks,
Seth Rowe [MVP]
values in the load method, but the values aren't persisted upon
leaving the load method.
To be honest, I can't think of a great explanation on why it doesn't
work, so I figured I'd post here and see if one of the guru's could
tell me exactly what's happening and why. I'm guessing this has to do
with the fact you need to pass the object by ref, which can't be done
with "this".
Here's a complete console application that demonstrates the behavior:
/////////////////////
using System;
namespace ConsoleApplication1
{
public class Program
{
public static void Main()
{
var fooObject = new FooObject();
fooObject.Load();
Console.WriteLine(fooObject.Name);
Console.WriteLine(fooObject.Description);
Console.Read();
}
}
public class FooObject
{
public string Name { get; set; }
public string Description { get; set; }
public void Load()
{
DALC.LoadFooObject(this);
}
}
public static class DALC
{
public static void LoadFooObject(FooObject fooObject)
{
/*
This of course works, but they don't want to do it
(long story)
fooObject.Name = "name";
fooObject.Description = "some
description";
*/
var temp = new FooObject()
{
Name = "name",
Description = "some description"
};
// This is the issue, the property values are set here,
but not
// persisted once we leave the method.
fooObject = temp;
}
}
}
/////////////////////
Thanks,
Seth Rowe [MVP]