I have two classes, which are passed to Serialization method and I would like to access two properties of these classes in Serialization method. The problem is that Serialization method parameter are passed as generic type and I do not know how to access properties of passed class in this case. The example below.
public class MyClass1
{
public string MyProperty1 { get; set; }
//These properties are shared in both classes
public bool Result { get; set; }
public string EngineErrorMessage { get; set; }
}
public class MyClass2
{
public string MyProperty2 { get; set; }
//These properties are shared in both classes
public bool Result { get; set; }
public string EngineErrorMessage { get; set; }
}
//The method is used to serialize classes above, classes are passed as generic types
public void Serialization<T>(ref T engine)
{
try
{
//Do some work with passed class
}
catch (Exception e)
{
//If Exception occurs I would like to write values to passed class properties, how to do that?
Result = false;
EngineErrorMessage = e.Message;
}
}
Full method code
public void Submit<T>(ref T engine)
{
try
{
var workingDir = Path.Combine(Settings.FileStoragePath, Helpers.GetRandomInt(9).ToString());
Directory.CreateDirectory(workingDir);
var inputFile = Path.Combine(workingDir, Settings.InFileName);
var outputFile = Path.Combine(workingDir, Settings.OutFileName);
var deleteFile = Path.Combine(workingDir, Settings.DelFileName);
try
{
using (var stream = new FileStream(inputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
Serializer.Serialize(stream, engine);
}
CheckStatus(outputFile);
using (var stream = new FileStream(outputFile, FileMode.Open, FileAccess.Read, FileShare.None))
{
engine = Serializer.Deserialize<T>(stream);
}
}
finally
{
File.Create(deleteFile).Dispose();
}
}
catch (Exception e)
{
//ToDo: Not implemented yet.
/* Result = false;
ErrorMessage = e.Message;*/
}
}
Declare an interface containing the properties
ResultandEngineErrorMessage. Now you have two options:engineto the interface mentioned above. If the cast succeeds, write the propertie values, otherwise do nothing.Sample: