Problems using a C# singleton in PowerShell - c#

I'm having some trouble getting my singleton class to cooperate when I try to load it into PowerShell. Specifically, I am getting the following error when I try to access the instance:
You cannot call a method on a null-valued expression.
At C:\Users\*Omitted*\Documents\visual studio
2012\Projects\ClassLibrary1\ClassLibrary1\bin\Debug\test.ps1:5 char:1
+ $test = [ClassLibrary1.Class1]::Instance.Foo()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
When I run this sample script:
$currentScriptDirectory = Get-Location
[System.IO.Directory]::SetCurrentDirectory($currentScriptDirectory.Path)
[Reflection.Assembly]::LoadFrom("ClassLibrary1.dll") | fl
[ClassLibrary1.Class1] | Get-Member -Static
$test = [ClassLibrary1.Class1]::Instance.Foo()
On this simple class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
private static Class1 instance = null;
private Class1()
{
}
public static Class1 Instance
{
get
{
if (null == instance)
{
instance = new Class1();
}
return instance;
}
}
public string Foo()
{
return "HI THERE";
}
}
}
Any ideas on how to get rid of this error without changing the class from a singleton? I've inherited the class I'm working with and can't change its architecture.

The main problem is that you got static and instance confused. Static means it's class-level, e.g. the instance. The Foo method should be instance, as that's seemingly what you want. Here's the fixed code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
private static Class1 instance = null;
private Class1()
{
}
public static Class1 Instance
{
get
{
if (null == instance)
{
instance = new Class1();
}
return instance;
}
}
public string Foo()
{
return "HI THERE";
}
}
}
However, this is not a bulletproof singleton pattern. Jon Skeet has made some good ones, here.
Here's a proper implementation of it:
public sealed class Class1
{
private static readonly Lazy<Class1> lazy =
new Lazy<Class1>(() => new Class1());
public static Class1 Instance { get { return lazy.Value; } }
private Class1()
{
}
public string Foo()
{
return "HI THERE";
}
}

Related

error CS0116: A namespace cannot directly contain members such as fields or methods- hand writing coding using notepad

Getting the error on line 16, with the foreach. My professor wont email fast enough and the due date is in a few hours! I think I am missing a list or something. I think the d after the double is incorrect. Any help is appectiated!
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class Starbucks
{
public static void Main()
{
double[] x = {4.2, 5.7, 3.6, 9.1, 2.7, 8.4 };
}
}
static void MyGenerics(double x)
{
foreach (double d in x)
{
MessageBox.Show(x);
}
}
That's because you have defined the MyGenerics() method outside the class Starbucks. Move it inside the class. Error message is exactly telling the same thing. Your code should look like
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class Starbucks
{
public static void Main()
{
double[] x = {4.2, 5.7, 3.6, 9.1, 2.7, 8.4 };
MyGenerics(x);
}
static void MyGenerics(double[] xx)
{
foreach (double d in xx)
{
MessageBox.Show(d);
}
}
}
This problem can be caused by bad indentation. For example:
using System;
namespace Interrogacion_1.Model
{
interface IClass
{
public string Name { get; set; }
}
{
Console.WriteLine("HELLO WORLD"); #here error cs0116
}
}
The correct way would be:
using System;
namespace Interrogacion_1.Model
{
interface IClass
{
public string Name { get; set; }
public void Imprimir()
{
Console.WriteLine("HELLO WORLD");
}
}
}

Create new instance of private class in another private class

Is it possible to create an instance of a private class in another private class? (Not counting within the main() program.)
And also, is it possible for a method in a private class to return a private type object?
This question came because I was following Scott Allen from PluralSight on C# Fundamentals With C#5. And on lesson 2 about classes and objects, he has a code example like this:
public GradeStatistics ComputeStatistics()
{
GradeStatistics stats = new GradeStatistics();
...
...
}
with GradeStatistics defined in a separate class file like:
class GradeStatisticss
{
}
Inlined comment: I am not talking about nested classes. What I meant is, you have two classes (separate files) and I am wondering if one class can create an instance of another class (knowing they are both private).
Edited with examples:
private class Example1
{
}
private class Example2
{
public Example1 DoSomeComputation()
{
return new Example1();
}
}
private class Example3
{
Example1 ex1 = new Example1();
}
Is Example3 able to create ex1? Can Example2 return a new instance of Example1?
Is it possible to create an instance of a private class in another private class?
Only if the private class for which you want to create an instance is declared inside the private class that wants to create the instance. If they are not nested, it's not possible.
Is it possible for a method in a private class to return a private type object?
Yes, it can.
Here's some code showing everything together:
public class Tester {
private class ThePrivateCreator {
private class TheOtherPrivateClass {
}
public Object createObject() {
return new TheOtherPrivateClass();
}
}
public void canWeDoThis() {
ThePrivateCreator c = new ThePrivateCreator();
Console.WriteLine(c.createObject());
}
}
class Program
{
public static void Main(string[] args) {
Tester t = new Tester();
t.canWeDoThis();
}
}
No. A private class cannot be accessed by another class in a different file. The reason why is that the modifier private is meant to encapsulate the data or method inside of that class. You should use the public or internal modifier if you want to access a class from a different class that is not nested. If it is nested, you can also use the protected modifier.
Not sure exactly what you had in mind, but here's one possible example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
private1 p1 = new private1();
private2 p2 = p1.foo();
Console.WriteLine(p2.Value);
Console.ReadLine();
}
private class private1
{
public private2 foo()
{
private2 p2 = new private2("I was created inside a different private class!");
return p2;
}
}
private class private2
{
private string _value;
public string Value
{
get { return _value; }
}
public private2(string value)
{
this._value = value;
}
}
}
}

Nunit is not running in any test method

I have two classes in class library
namespace ClassLibrary3
{
public class Class1
{
public string title;
public string author;
public Class1(string title, string author)
{
this.title = title;
this.author = author;
}
}
}
Another class
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ClassLibrary3
{
class Class2
{
private Hashtable books;
public Class2()
{
books = new Hashtable();
}
public void addBook(Class1 book)
{
books.Add(book.title, book);
}
public Class1 getBook(String title, String author)
{
return (Class1)books[title];
}
public void removeBook(string title)
{
if (books[title] != null)
books.Remove(title);
}
}
}
And my test is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Collections;
namespace ClassLibrary3
{
[TestFixture]
class TEST
{
[Test]
public void getbooktest()
{
Class1 c1 = new Class1("story", "James");
Class2 c2 = new Class2();
Assert.AreEqual("story", c2.getBook("story", "James"));
}
}
}
Basicly the problem is Nunit doesnt test it. It finds the dll. Loads the test class. But dont come upto the test method.
Please any idea..........
NUnit can't see your TEST class unless you mark it as public, change it to
[TestFixture]
public class TEST
{
...
Side note, consider giving it a better name than TEST ;-)

Class Property inside Class On Separate Thread

I have a host class which launches an instance of another class on a new thread like so:
I am referencing this MSDN article according to which, Class2.P1 should NOT be null.
LINK: http://msdn.microsoft.com/en-us/library/system.threading.threadstart.aspx
Am I missing anything obvious?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
new Host().DoWork();
}
}
public class Host {
Class2Parent c = new Class2();
Thread t;
public void DoWork() {
c.P1 = new Class3();
t = new Thread(c.Start);
t.Start();
}
}
public class Class2Parent {
public Class3 P1 = null;
public virtual void Start() {}
}
public class Class2 : Class2Parent {
public Class3 P1 = null;
public override void Start() {
Console.WriteLine(P1 == null); // this is always true
}
}
public class Class3
{}
}
You can try to create a new thread using a timer variable just like that :
private Timer m_RequestTimer;
public void Begin()
{
// Timer check
if (m_RequestTimer != null)
{
m_RequestTimer.Change(Timeout.Infinite, Timeout.Infinite);
m_RequestTimer.Dispose();
m_RequestTimer = null;
}
m_RequestTimer = new System.Threading.Timer(obj => { c.Start(); }, null, 250, System.Threading.Timeout.Infinite);
}
}
where m_RequestTimer is an attribute of your class host and Begin a method of Host.
I hope it will help you =)

C#: Access Enum from another class

I know I can put my enum at the Namespace area of a class so everyone can access it being in the same namespace.
// defined in class2
public enum Mode { Selected, New, }
What I want is to access this enum from
public class1
{
var class2 = new class2();
// Set the Mode
class2.Mode = Model.Selected
}
Is this somehow possible without using namespace area?
You can declare an enum outside of a class:
namespace MyNamespace
{
public enum MyEnum
{
Entry1,
Entry2,
}
}
And then you can add using MyNamespace; where it needs to be used.
Aaron's answer is very nice but I believe there is a much better way to do this:
public static class class1
{
public void Run()
{
class2.Mode mode = class2.Mode.Selected;
if (mode == class2.Mode.Selected)
{
// Do something crazy here...
}
}
}
public static class class2
{
public enum Mode
{
Selected,
New
}
}
No point over complicating this. It is a simple task.
All the Best
Chris.
If you are trying to do what is described below it will not work...
public class MyClass1
{
private enum Mode { New, Selected };
public Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will not work due to protection level
myClass1.ModeProperty = MyClass1.Mode.
}
}
What you could do however is below, which will work...
public interface IEnums
{
public enum Mode { New, Selected };
}
public class MyClass1
{
public IEnums.Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will work
myClass1.ModeProperty = IEnums.Mode.New;
}
}
Yes:
class2.Mode = class2.Mode.Selected
But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile. Either the enum or the property will need to be named something else. Your class name and variable name conflict too, making this a bit more complex.
To make this a more generic answer, if you have this:
public class Foo
{
public SomeEnum SomeProperty { get; set; }
public enum SomeEnum {
Hello, World
}
}
Then this code will assign an enum value to the property:
Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;
I ended up solving my issue by changing it to a namespace accessor, found by utilizing Intellisense. I thought the enum was in the class, not just the namespace. If it was in the class, I would recommend moving it out of the class.
namespace ABC.XYZ.Contracts
{
public class ChangeOrder : BaseEntity, IAuditable
{
...
}
public enum ContractorSignatureType
{
A,
B,
V
}
}
ContractorSignatureType = Contracts.ContractorSignatureType.B,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int)temp.names.nikk);
Console.ReadKey();
}
}
}
//by using this you can access the value of enum.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(temp.names.nikk);
Console.ReadKey();
}
}
}

Categories

Resources