Any meant where to locate the using? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
WiresharkFile abstract class:
public abstract class WiresharkFile
{
private PlayBehavior _playBehavior;
public void Transmit()
{
_playBehavior.Transmit();
}
public virtual void Dispose()
{
// Implemented inside inherit classes.
}
}
Play options abstract class:
public abstract class PlayBehavior
{
public WiresharkFile wiresharkFile;
public abstract void Transmit();
}
Play options son class:
public class Normal : PlayBehavior
{
public override void Transmit()
{
using (this.wiresharkFile)
{
}
}
}
So i have this derived class:
public class Libpcap : WiresharkFile, IDisposable, IEnumerable<Packet>
{
private BinaryReader binaryReader;
public void Dispose()
{
if (binaryReader != null)
binaryReader.Close();
}
...
// Severl methods
...
public override void SendPackets()
{
base.Transmit();
}
}
My question:
Inside this Libpcap class when call base.Transmit(): where to use the using ?
Inside this Libpcap class SendPackets():
public override void SendPackets()
{
using(this)
{
base.Transmit();
}
}
Or inside Normal class Transmit():
public class Normal : PlayBehavior
{
public override void Transmit()
{
using (this.wiresharkFile)
{
}
}
}

Calling using(this) never makes sense. It means you're calling Dispose on yourself, which means that A) your class will be at an undefined state at the end of the using block, and B) code calling you will see you're IDisposable and expect to be able to control your lifetime, but you're actually controlling it yourself from within your code.
If your Libpcap's lifetime ends after the Transmit call, you can use using on it from your PlayBehavior class - it holds the reference to it, so it controls its lifetime.
Implementing IDisposable is a contract. By doing so, you're saying "My operation holds references to unmanaged resources (files, tcp connections, etc), and you, my caller, need to call my Dispose method when you're done with me to release them". If this is not the usage contract that WiresharkFile expects, don't implement IDisposable.
If you have unmanaged resources that are created and released as part of your normal operations, but which doesn't require your caller to explicitly release, simply do it yourself - release an internal unmanaged resource when you're done with it.

Related

Virtual void not being overridden with override keyword in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to make a class the user of my library can derive from and then access a method for debugging the times of each action. Because my main debug method, where most information is stored, is static (and needs to be), I cannot use it to derive a class or add an overridable method in it. To combat this, I added the following code:
public static class Debug
{
internal static void CallObjectEvent(string log)
{
new Call().CallEvent(new Log(log, Timer.GetTime()));
}
}
internal class Call : IDebug
{
internal void CallEvent(Log log)
{
base.Event(log);
}
}
public class IDebug
{
public virtual void Event(Log log) {Console.WriteLine("test");}
}
class Program : IDebug
{
public override void Event(Log log)
{
Console.WriteLine(log.log);
}
}
Every time, it outputs 'test' instead of the log message. How can I fix this? Are there any alternatives to do the same thing?
Your Debug.CallObjectEvent() method explicitly instantiates a Call object and calls the overridden method in that class:
public static class Debug
{
internal static void CallObjectEvent(string log)
{
new Call().CallEvent(new Log(log, Timer.GetTime()));
}
}
The CallEvent() method in the Call class simply calls base.Event(), which resolves to IDebug.Event(). The Program.Event() override is never invoked because Program is not in the class hierarchy at the point of the call.
When you override a method or property, the override applies only to the class where it is defined (and all of its child classes, of course). Since Program isn't a parent class of Call there's no reason why its overrides would ever be referenced.
From what you've written it looks like you're trying to set up a system for handling different log outputs depending on the program's requirements. You need a way to register the appropriate log writer for your program. Something like:
public interface ILogWriter
{
void Event(Log item);
}
private class DefaultLogWriter : ILogWriter
{
public void Event(Log item)
{
Console.WriteLine($"[test] {item.Time} {item.Message}");
}
}
internal static class Debug
{
private static ILogWriter _writer = null;
public static ILogWriter Writer
{
get
{
if (_writer == null)
_writer = new DefaultLogWriter();
return _writer;
}
set => _writer = value;
}
internal static void CallObjectEvent(string log)
{
Writer.Event(new Log(log, Timer.GetTime()));
}
}
class Program
{
private class MyLogWriter : ILogWriter
{
public void Event(Log item)
{
Console.WriteLine($"[MyLogWriter] {item.Time} {item.Message}");
}
}
static void Main()
{
Debug.Writer = new MyLogWriter();
Debug.CallObjectEvent("Test message.");
}
}

Force Method to be called after overloaded constructor is called from the Super-class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a unity3d project where I have an abstract object that I will be calling from other objects. I want all my subclasses to call a certain virtual method after they finish constructing. Essentially the base constructor will be called, then the overloaded constructor, and finally my method, but I want this behavior defined from the base object.
You can force your subclass to implement an abstract method called Initialize() and then choose the order of calls in your base class :
public abstract class MyBaseClass
{
public abstract void Initialize();
public MyBaseClass()
{
// Code of the constructor of the base class
// Calling the subclass
Initialize();
// Finally call the special method
MySpecialMethod();
}
private void MySpecialMethod()
{
// Some code here
}
}
public class MySubclass : MyBaseClass
{
public override void Initialize()
{
// Some code here
}
}

How can I share the same instance to all derived classes in multiple threads with C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am using command pattern in C#.
There is a class that contains some properties named RequiredData.
public class RequiredData
{
public Class1 class1 { get; set; }
public int value1 {get; set;}
}
There is an abstract class BaseCommand and there are some derived classes like command1 , command2 etc.
abstract class BaseCommand : ICommand { }
The commands operate some actions like:
command1.Execute();
command2.Execute();
I want during the whole process to have a shared RequiredData object which can be updated and used from all commands.
For example:
in command1 Execute method to access the value1 like :
RequiredData.Value1 = 5
and then in command2 Execute method to have this value like
var k = RequiredData.Value1 //and be 5..
or RequiredData.Class1.something = "something"
I tried this one in the base class:
abstract class BaseCommand : ICommand
{
//or protected and not private...
public static RequiredData RequiredData = new RequiredData();
}
is this thread-safe?
What changes needed here for a thread-safe solution?
You could solve this by using several methods.
Pass the shared instance into the constructor
Singleton pattern/static could help, but is more restricted.
Reminder is, if you use the class on different thread, you need to care about thread safety.
Normally I avoid a static object that can be readed/writed by multiple threads. I advise you to try to get rid from this.
But... you need to be sure, that the object/reference types are not accessible from the outside.
like:
// you could create the locking in this class, but the class1 property is a
// reference type, so just locking in the property is not enought, it
// goes wrong when the Class1 has properties itself. (then these will be
// altered outside the lock..
// I choose to wrap the whole object and only returning value types
public class RequiredData
{
public Class1 class1 { get; set; }
public int value1 {get; set;}
}
abstract class BaseCommand : ICommand
{
// protected.. should not be accessable from the outside..!
protected static RequiredData RequiredData = new RequiredData();
public int GetValue()
{
lock(RequiredData)
return RequiredData.value1;
}
public void SetValue(int value)
{
lock(RequiredData)
RequiredData.value1 = value;
}
// or you could wrap this in a property
public int Value
{
get { return lock(RequiredData) RequiredData.value1; }
set { lock(RequiredData) RequiredData.value1 = value; }
}
public string GetSomething()
{
// try to avoid returning reference types, but the can be referenced from outside the object.
lock(RequiredData)
return RequiredData.Class1.something;
}
}
So the locking should be inside the BaseCommand. And the BaseCommand should be responsible for communicating with the RequiredData. (so no other object could have a reference to the RequiredData)
Like I said: Multithreading / static read/writer = playing with fire.
If you have many readers/writers you should have a look at the ReaderWriterLock(Slim). Because multiple threads can read simultaneously and only one writer is active.

How can i create dynamic variables on the fly in c# using Reflection? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm creating a simulator of ecosystems where species can be used to simulate various diseases, my problem is that I start using 4 species but if I need more ... I need more variables to store, my question is, Is there any way through Reflection to let me create dynamic variables during the execution of an event in my program? Thank you! i'm using Windows Presentation Foundation and C#
The normal way to handle this is to have a base class for your disease species and then use a collection to hold them all:
public abstract class DiseaseBase
{
public abstract void Spread();
}
public class Anthrax : DiseaseBase
{
public override void Spread()
{
GetPostedToPolitician();
}
}
public class BirdFlu : DiseaseBase
{
public override void Spread()
{
Cluck();
SneezeOnHuman();
}
}
public class SwineFlu : DiseaseBase
{
public override void Spread()
{
//roll in mud around other piggies
}
}
public class ManFlu : DiseaseBase
{
public override void Spread()
{
//this is not contagious
//lie in bed and complain
//get girlfriend to make chicken soup
//serve chicken soup with beer and baseball/football/[A-Za-z0-9]+Ball
}
}
public List<DiseaseBase> DiseaseCollection = new List<Disease>();
So everything gets stored in the collection as the base class (DiseaseBase), and with the appropriate use of abstract methods in the base and/or interfaces you can always handle each disease instance as the base object.

Recommend a design pattern [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
An application I'm working on processes Work Items. Depending on the state of a work item there are a number of actions available. "Complete" "Cancel" "Reassign" etc...
To provide the functionality for the actions I currently have an interface that looks something like this...
public interface IActionProvider{
public void Complete(WorkItem workItem);
public void Cancel (WorkItem workItem);
public void Reassign(WorkItem workItem);
}
Then based on other details of the work item I have concrete implementations of the interface. Just for example...
public class NormalActionProvider :IActionProvider
{
...
}
and
public class UrgentActionProvider : IActionProvider
{
....
}
The problem is, if I want to add a new action, say... "Delegate" I have to update the interface which of course has effects on all of the implementations.
Does this violate the Open/Close Principle? Can you recommend a design pattern or refactor that may help me here?
Looks like command pattern would be suitable. You can modify/add more commands. The command classes are decoupled from the main program.
public interface IActionProvider{
public void execute(WorkItem item,ActionType actionType);
}
ActionType represents Complete,Cancel & so on. You can keep adding more action types & plugin appropriate command classes.
You could always add a Decorator to the IActionProvider interface (follow the Decorator design pattern).
It depends on what you really are trying to accomplish with your IActionProvider. If you really want to make it so that every implementation must be able to perform all of the actions that you consider to be important, then that should be a part of the interface that they implement. Interfaces work best if they are well-planned ahead of time so they don't have to change continually.
But it sounds like you don't necessarily want all actions to be implemented by all providers. I'd need to know more details to be able to give good advice, but one example would be to have the providers initialize themselves against a kind of event Bus. They could subscribe to those events that they care about, and perform actions only for the events that make sense for the specific implementation.
"Depending on the state of the workitem", brings the State Design Pattern
One way or another, you'll have to refactor you interface and eventually break client contracts.
If i have understood your problem correctly, then you have a WorkItemProcessor whose state changes depending
on the WorkItem Sent to it.
Therefore your WorkItemProcessor becomes
// Context
public class WorkItemProcessor
{
public IState CurrentState { get; set; }
public WorkItemProcessor(IState initialState)
{
CurrentState = initialState;
}
public void Process(WorkItem workItem)
{
CurrentState.Handle(this, workItem);
}
}
Then we define multiple states that the WorkItemProcessor could potentially be in
// State Contract
public interface IState
{
void Handle(WorkItemProcessor processor, WorkItem item);
}
// State One
public class CompleteState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CompletenessConditionHoldsTrue ? (IState) this : new CancelState();
}
}
// State Two
public class CancelState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CancelConditionHoldsTrue ? (IState) this : new CompleteState();
}
}
Assuming your WorkItem Looks like
// Request
public class WorkItem
{
public bool CompletenessConditionHoldsTrue { get; set; }
public bool CancelConditionHoldsTrue { get; set; }
}
To put it all together
static void Main()
{
// Setup context in a state
WorkItemProcessor processor = new WorkItemProcessor(new CancelState());
var workItem1 = new WorkItem { CompletenessConditionHoldsTrue = true };
var workItem2 = new WorkItem { CancelConditionHoldsTrue = true };
// Issue requests, which toggles state
processor.Process(workItem1);
processor.Process(workItem2);
Console.Read();
}
Hope this gets you closer. Cheers.
I would also choose the command pattern. As an enhancement, you can combine it with the abstract factory method, so you can have a factory class for each command class, and all those factories implement a common factory interface.
For example:
// C#
public interface ICommand { void Execute(); }
public interface ICommandFactory { ICommand Create(); }
public class CommandFactoryManager
{
private IDictionary<string, ICommandFactory> factories;
public CommandFactoryManager()
{
factories = new Dictionary<string, ICommandFactory>();
}
public void RegisterCommandFactory(string name, ICommandFactory factory)
{
factories[name] = factory;
}
// ...
}
This way, you can register new command factories dynamically. For example, you can load a DLL at runtime and fetch all the classes that implement the ICommandFactory interface using reflection, and you have a simple plugin system.

Categories

Resources