Bill Greer
Bill Greer

Reputation: 3156

Confusing C# Constructor

I ran across some code today that is a little confusing to me. I have a class called Operator. Help me understand what is happening in the constructor of the class. I do not understand why it has the UsedImplicity attribute and I do not know what "this(r => { })" is accomplishing.

public class Operator
{
[NotNull] readonly IUnityContainer _container;
[NotNull] readonly ServerWrapper _server;

[UsedImplicitly]
public Operator()
  : this(r => { })
{
}

UPDATE - The other constructor:

public Operator([NotNull] Action<IUnityContainer> register)
{
  _container = new UnityContainer()
    .RegisterType<ISettingsReader, MessageBusSettingsReader>(
      new ContainerControlledLifetimeManager())
    .RegisterType<IImpersonationStrategyFactory, ImpersonationStrategyFactory>();

  register(_container);

  _operator= new OperatorWrapper(_container.Resolve<ISettingsReader>());
}

Upvotes: 2

Views: 213

Answers (1)

Cee McSharpface
Cee McSharpface

Reputation: 8726

The constructor provides a callback mechanism: On instantiating an Operator, you as the caller may pass in a method pointer (lambda or not) with the Action<IUnityContainer> signature, that would be a void Callback(IUnityContainer c) for example, or a c => { do_something_with_c(c); }.

The default constructor, that is the one without arguments, chains the constructor with an empty method body, it basically ignores (throws away) the container callback. It does so because it needs to execute the initialization code in that second constructor, but cannot call it without its required argument.

Second subquestion: UsedImplicitly is to get rid of warnings when a symbol is never referenced but meant to be used by reflection or called externally, is well documented here.

Upvotes: 4

Related Questions