Need of New keyword in multilevel inheritance c# - c#-4.0

Hello this question is regarding when exactly New keyword i;e Method hiding in base class can be done.
static void Main(string[] args)
{
A a = new A();
a.calculatebnft();
a = new B();
a.calculatebnft();
a = new C();
a.calculatebnft();
a = new Program();
a.calculatebnft();
Console.ReadKey();
}
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
return bnft;
}
}
class A
{
//my code here
public virtual string calculatebnft()
{
string bnft = "";
Console.WriteLine("A");//my code here
return bnft;
}
}
class B : A
{
//my code here
public override string calculatebnft()
{
string bnft = "";
Console.WriteLine("B");//my code here
return bnft;
}
}
class C : B
{
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("C");
return bnft;
}
}
When above program is executed output is
A
B
B
B
in this case New Keyword in class C not hiding method in class B? what is the reason behind it.
Sorry am new to .Net and if my question is too basic

Related

without resolveStrategy=DELEGATE_FIRST properties end up as binding variables

I'm trying to write java beans that can be loaded from a Groovy config file. The config format expects properties in closures and if I don't call c.setResolveStrategy(Closure.DELEGATE_FIRST) then all properties set inside the closures end up as binding variables. My program outputs:
In closure
confpojo.myTestProp: null
binding.myTestProp: true
confpojo.app.myOther.myTestSubProp: null
binding.myTestSubProp: true
In this answer https://stackoverflow.com/a/10761284/447503 they don't change the default resolveStrategy and it seems to work. What's the difference? configaaa.groovy:
app {
println 'In closure'
myTestProp = true
myOther {
myTestSubProp = true
}
}
_
public abstract class AaaTestGroovyConfig extends Script {
public static class App {
public void myOther(final Closure c) {
c.setDelegate(myOther);
// c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.call();
}
private Boolean myTestProp;
private final Other myOther = new Other();
public Boolean getMyTestProp() {
return myTestProp;
}
public void setMyTestProp(final Boolean active) {
this.myTestProp = active;
}
}
public void app(final Closure c) {
c.setDelegate(app);
// c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.call();
}
private App app = new App();
public static void main(final String[] args) throws Exception {
final CompilerConfiguration cc = new CompilerConfiguration();
cc.setScriptBaseClass(AaaTestGroovyConfig.class.getName());
// final ClassLoader cl = AaaTestGroovyConfig.class.getClassLoader();
final Binding binding = new Binding();
final GroovyShell shell = new GroovyShell(binding, cc);
final Script script = shell.parse(new File("configaaa.groovy"));
final AaaTestGroovyConfig confpojo = (AaaTestGroovyConfig) script;
// ((DelegatingScript) script).setDelegate(confpojo);
script.run();
System.out.println("confpojo.myTestProp: " + confpojo.app.myTestProp);
printBindingVar(binding, "myTestProp");
System.out
.println("confpojo.app.myOther.myTestSubProp: " + confpojo.app.myOther.myTestSubProp);
printBindingVar(binding, "myTestSubProp");
}
private static void printBindingVar(final Binding binding, final String name) {
System.out
.println(
"binding." + name + ": " + (binding.hasVariable(name)
? binding.getVariable(name)
: ""));
}
public static class Other {
private Boolean myTestSubProp;
public Boolean getMyTestSubProp() {
return myTestSubProp;
}
public void setMyTestSubProp(final Boolean myTestSubProp) {
this.myTestSubProp = myTestSubProp;
}
}
public App getApp() {
return app;
}
public void setApp(final App app) {
this.app = app;
}
}
because the default value is OWNER_FIRST
https://docs.groovy-lang.org/latest/html/api/groovy/lang/Closure.html#OWNER_FIRST
and you have 2 levels of closures so - owners are different for them
try something like this and you'll see the difference
app {
println "delegate=$delegate owner=${owner.getClass()}"
myOther {
println "delegate=$delegate owner=${owner.getClass()}"
}
}
PS: let me suggest you to make your code groovier:
//generic config class
class MyConf {
private HashMap objMap
static def build(HashMap<String,Class> classMap, Closure builder){
MyConf cfg = new MyConf()
cfg.objMap = classMap.collectEntries{ k,cl-> [k, cl.newInstance()] }
cfg.objMap.each{ k,obj->
//define method with name `k` and with optional closure parameter
cfg.metaClass[k] = {Closure c=null ->
if(c) {
// call init closure with preset delegate and owner
return c.rehydrate(/*delegate*/ obj, /*owner*/cfg, /*this*/cfg).call()
}
return obj //return object itself if no closure
}
}
cfg.with(builder) // call root builder closure with cfg as a delegate
return cfg
}
}
//bean 1
#groovy.transform.ToString
class A{
int id
String name
}
//bean 2
#groovy.transform.ToString
class B{
int id
String txt
}
//beans init
def cfg = MyConf.build(app:A.class, other:B.class){
app {
id = 123
name = "hello 123"
other {
id = 456
txt = "bye 456"
}
}
}
//get initialized beans
println cfg.app()
println cfg.other()

How to properly call GroovyScriptEngine?

I'm testing Groovy but I can't figure out how to properly call GroovyScriptEngine. It keeps producing an error below.
org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack
Song.Groovy
class Song {
def args;
{
println "Song has been called." + args;
}
String getArtist(){
return "sdfsdf";
}
public String toString(){
return "Hey!";
}
}
Java Main ->
String[] paths = { "C:\\Users\\User\\workspace\\GroovyTest\\src\\groovy" };
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
Object s = "Default...";
binding.setVariable("args", s);
gse.run("Song.groovy", binding);
the args variable also produce null..
What to do ?
You are loading a class!
If you want to test your class, try something like this in the end of your Song.groovy:
// Instantiate an object of your class and use some methods!
def song = new Song()
println song.getArtist();
When you run
gse.run("Song.groovy", binding);
You are basically loading your class, but you are not doing anything with it.
See this example here
(Posted on behalf of the OP):
Working code:
Test1.java
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
public class Test1 {
public static void main(String[] args) throws Exception {
String[] paths = { "C:\\Users\\User\\workspace\\GroovyTest\\src\\groovy" };
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
binding.setVariable("args", "Test Data");
String result = (String) gse.run("File1.groovy", binding);
System.out.println("Groovy Result: " + result);
}
}
File1.groovy
package groovy;
class Greeter {
String sayHello(String data) {
def greet = data;
return greet
}
}
static void main(String[] args) {
def greeter = new Greeter()
return greeter.sayHello(args);
}

Vala files import

I have a problem when work with properties in separated files in Vala Language
The Main.vala file is
using Teste;
using Cagado;
static int main(string[] args)
{
GUI gui = new GUI();
stdout.printf("%d\n", gui.idade);
return 0;
}
The HelloVala.vala is:
namespace Teste
{
public class Person : Object
{
private int _age = 32;
public int age
{
get { return _age; }
set { _age = value; }
}
}
}
The Cagado.vala is:
using Teste;
namespace Cagado
{
public class GUI : Object
{
Person _person = new Person();
_person.age = 35;
private int _idade;
public int idade
{
get { return _idade; }
set { _idade = value; }
}
}
}
When i compile this code, the compile gives me the message error:
Cagado.vala:9.15-9.15: error: syntax error, expected identifier
_person.age = 35;
^
I program in C# and this not happened in C# oriented object system.
Someone could explain this?
The problem is this:
public class GUI : Object
{
Person _person = new Person();
_person.age = 35; // <--
...
You can't put arbitrary code inside of the class itself, only declarations. What you need to do is something like
public class GUI : Objects
{
Person _person = new Person();
construct {
_person.age = 35;
}
You could also modify add a constructor to the Person class:
namespace Teste
{
public class Person : Object
{
private int _age = 32;
public int age
{
get { return _age; }
set { _age = value; }
}
public Person(int age) {
GLib.Object (age: age);
}
}
}
Then do
public class GUI : Object
{
Person _person = new Person(35);

Thread safe method invocation

Please let me know below method invocation is thread safe or not.
I am calling ThreadStartMain on my main thread and create new threads and invoke A_GetCounryName method on new instance.
Since i am always calling via new instance i think this is thread safe even though i am having instance variables in some classes.
class MyThread
{
private void ThreadStartMain()
{
for (int i = 0; i < 5; i++)
{
A a = new A();
ThreadStart start = new ThreadStart(a.A_GetCounryName);
Thread t = new Thread(start);
t.Start();
}
}
}
class A
{
public B GetNewObject()
{
B bObj = new B();
return bObj;
}
public void A_GetCounryName()
{
B b=GetObject();
string cName=b.B_GetCoutryName();
}
}
class B
{
C cObj = null;
public B()
{
cObj = new C();
cObj.Prop1 = 1;
cObj.Prop1 = 2;
cObj.Prop1 = 3;
}
public string B_GetCoutryName()
{
string countryName= cObj.C_GetCoutryName();
return countryName;
}
}
class C
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public int Prop3 { get; set; }
public string C_GetCoutryName()
{
string name = "Italy";
return name;
}
}
Yes, this is safe because your threads do not share state. More precisely: They do not access common storage locations.

Accessing the Properties of a class dynamically

Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.
public Class1
{
public const prop1="Some";
}
public Class2
{
public const prop1="Some";
}
And in my code I am getting my class name like this
string classname="Session["myclass"].ToString();";//Say I have Class1 now.
And I want to get the prop1 value .
Something like
string mypropvalue=classname+".prop1";//my expected result is Some
///
Type typ=Type.GetType(classname);
Please help me in getting this
Reflection
var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
for static:
var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);
Class reference from string
EDIT (I made example):
class Program
{
static void Main(string[] args)
{
var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
//This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
var prop1
= ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(prop1.GetValue(ty.Name, null));
Console.ReadLine();
}
}
public static class Foo
{
private static string a = "hello world";
public static string Temp
{
get
{
return a;
}
}
}
Msdn
you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}

Resources