Why cannot we do (void)10? - c#-4.0

I know it is a foolish question to ask but after reading the very first answer of Mr. Matteo Italia If void() does not return a value, why do we use it?, I have performed this small experiment in C# 4.0
class Program
{
static void Main(string[] args)
{
var x = (int)5; // worked as expected
var x1 = (void)10; // Error 'void' cannot be used in this context
}
}
Why?

Void is not a data type and hence we cannot cast anything to void type. I believe you are probably coming from a C world where we could have a void* which is very different.

Related

Calling Overload Methods

I can't seem to make this work let alone compile and I am at loss at how to fix it. My teacher gave us the following code (simplified for question's sake):
public static void doing1(String s) {
// add code here
}
public static void doing2(char start, char end) {
// add code here
}
public static int doing3(int num) {
// add code here
}
public static void doing4(Scanner keyboard) {
// add code here
}
I know what needs to go in each method (the work I mean) I just don't know how to print it out in the main method. We cannot change the code given to us, only add to it.
Thank you!
Overloading a method means having the same method name but the method signature (the parameters passed in) is different. So, what you have isn't actually an overload, it is for unique methods because they all have different names. As far as not compiling... what you posted looks fine - perhaps you have an error above or below that code. I believe this is what you are looking for:
public static void doing(String s) {
// add code here
}
public static void doing(char start, char end) {
// add code here
}
public static int doing(int num) {
// add code here
}
public static void doing(Scanner keyboard) {
// add code here
}
Here's a reference on overloads from the almighty John Skeet

What does it mean for void to be a "first class type"?

As the title says, and what are the benefits of this? The question was inspired by Microsoft's research language.
Being a first-class type means void could be used anywhere a type annotation is allowed. In C#, void can only be used as a return type for a method, but all of the following are illegal:
// A void parameter type.
int SomeMethod(void parameter) { ... }
// A void type argument.
List<void>
// A void variable.
void Main()
{
void someVar;
}
Java does have a first-class void type, spelled Void (note the capital "V"). It's useful sometimes in generics. It only has one value, null.
If void is a first class type then you can use it when defining variables. I think a void variable could be used as a pointer to pass a something like a function or an object if you recast it I guess. It would give you an ability to do dynamic type casts.

QtConcurrent::map() with member function = can not compile

My project is to create a small program which demonstrates the work of a search engine: indexing and returning result for arbitrary queries. I've done the work with the indexer part and now I want to improve it with indexing multiple files at once. The MainWindow class is here:
class MainWindow : public QMainWindow
{
Q_OBJECT
.....
private:
Indexer * indexer;
QStringList fileList;
....
void index(QStringList list);
void add(const QString &filename);
}
This is the implementation of add (add need to access fileList to avoid index the same files again, thus it can not be static method):
void MainWindow::add(const QString &filename)
{
if (!fileList.contains(filename))
{
indexer->addDocument(filename.toStdString());
fileList.append(filename);
qDebug() << "Indexed" << filename;
emit updatedList(fileList);
}
}
The implement of index method is to receive a file lists and call add upon each file name:
void MainWindow::index(QStringList list)
{
....
QtConcurrent::map(list, &MainWindow::add);
....
}
The error I receive when compiling these code is:
usr/include/qt4/QtCore/qtconcurrentmapkernel.h: In member function 'bool QtConcurrent::MapKernel<Iterator, MapFunctor>::runIteration(Iterator, int, void*) [with Iterator = QList<QString>::iterator, MapFunctor = QtConcurrent::MemberFunctionWrapper1<void, MainWindow, const QString&>]':
../search-engine/mainwindow.cpp:361:1: instantiated from here
/usr/include/qt4/QtCore/qtconcurrentmapkernel.h:73:9: error: no match for call to '(QtConcurrent::MemberFunctionWrapper1<void, MainWindow, const QString&>) (QString&)'
/usr/include/qt4/QtCore/qtconcurrentfunctionwrappers.h:128:7: note: candidate is:
/usr/include/qt4/QtCore/qtconcurrentfunctionwrappers.h:138:14: note: T QtConcurrent::MemberFunctionWrapper1<T, C, U>::operator()(C&, U) [with T = void, C = MainWindow, U = const QString&]
/usr/include/qt4/QtCore/qtconcurrentfunctionwrappers.h:138:14: note: candidate expects 2 arguments, 1 provided
I'm not really familiar with how QtConcurrent works, and the documentation doesn't provide much details about it. I really hope that someone here can help. Thanks in advance.
To be able to call a pointer-to-member, you need, in addition to that functions formal arguments, an instance of that class (the this pointer that you get inside member functions).
There are two ways to handle this: create a simple functor to wrap the call, or use a lambda.
The functor would look like this:
struct AddWrapper {
MainWindow *instance;
AddWrapper(MainWindow *w): instance(w) {}
void operator()(QString const& data) {
instance->add(data);
}
};
And you'd use it like:
AddWrapper wrap(this);
QtConcurrent::map(list, wrap);
(Careful with the lifetime of that wrapper though. You could make that more generic - you could also store a pointer-to-member in the wrapper for instance, and/or make it a template if you want to reuse that structure for other types.)
If you have a C++11 compiler with lambdas, you can avoid all that boilerpalte:
QtConcurrent::map(list, [this] (QString const& data) { add(data); });
Note: I'm not sure how QtConcurrent::MemberFunctionWrapper1 got involved in your example, I'm not seeing it here. So there might be a generic wrapper already in Qt for this situation, but I'm not aware of it.

Using FieldInfo.SetValue with a DynamicObject as argument 2

I ran into a problem today when trying to set a field using FieldInfo.SetValue() passing a DynamicObject as the second argument. In my case, the field is a Guid and the DynamicObject should be able to convert itself to a one (using TryConvert) but it fails with an ArgumentException.
Some code that shows the problem:
// Simple impl of a DynamicObject to prove point
public class MyDynamicObj : DynamicObject
{
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
// Support converting this to a Guid
if (binder.Type == typeof(Guid))
{
result = Guid.NewGuid();
return true;
}
return false;
}
}
public class Test
{
public Guid MyField;
}
class Program
{
static void Main(string[] args)
{
dynamic myObj = new MyDynamicObj();
// This conversion works just fine
Guid guid = myObj;
var test = new Test();
var testField = typeof(Test).GetField("MyField");
// This, however, fails with:
// System.ArgumentException
// Object of type 'ConsoleApplication1.MyDynamicObj' cannot be converted to type 'System.Guid'.
testField.SetValue(test, myObj);
}
}
I'm not very familiar with the whole dynamicness of C# 4, but this felt to me like something that should work.. What am I doing wrong? Is there another way of doing this?
No, this shouldn't work - because the dynamic portion ends where your code ends. The compiler is calling a method with a signature of
void SetValue(Object obj, Object value)
That method call is dynamic, but it's just going to end up passing in a reference to the instance of MyDynamicObj. The call is resolved at execution time, but nothing in SetValue knows anything about the dynamic nature of the object whose reference you're passing in.
Basically you need to perform the dynamic part (the conversion in this case) in your code - the bit that involves the C# 4 compiler doing all its tricks. You've got to perform that conversion, and then you can call SetField.
To put it another way - it's a bit like calling SetField with a field of type XName, but passing in a string. Yes, there's a conversion from string to XName, but it's not SetField's job to work that out. That's the compiler's job.
Now, you can get this to work by making the compiler do some of the work, but you still need to do some with reflection:
static void Main(string[] args)
{
dynamic myObj = new MyDynamicObj();
var test = new Test();
var testField = typeof(Test).GetField("MyField");
var method = typeof(Program)
.GetMethod("Convert", BindingFlags.Static | BindingFlags.NonPublic);
method = method.MakeGenericMethod(testField.FieldType);
object converted = method.Invoke(null, new object[] {myObj});
testField.SetValue(test, converted);
}
static T Convert<T>(dynamic input)
{
return input;
}
You need an explicit cast to invoke the TryConvert:
testField.SetValue(test, (Guid)myObj);
Not sure if this is what you need though. Maybe there's some way to reflectively say ((DynamicObject)myObj).TryConvert(/*reflected destination type here*/, result)
Other attempts that failed, some of them require things like a certain interface be implemented, so they basically don't make use of TryConvert but maybe an alternative way to accomplish what you want:
Type secondType = testField.FieldType;
TypeConverter tc = TypeDescriptor.GetConverter(typeof(MyDynamicObj));
object secondObject = tc.ConvertTo(myObj,typeof( Guid));
//var secondObject = Convert.ChangeType(myObj, secondType);//Activator.CreateInstance(secondType);
//secondObject = myObj;
testField.SetValue(test, secondObject);

Threading from within a class with static and non-static methods

Let's say I have
class classA {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
class classB {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
static void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
Assuming that in classA and classB, the contents of threadMethod have no effect to anything outside of its inner scope, does making threadMethod in classB static have any functional difference?
Also, I start two threads that use the same method in the same class. Does each method get its own stack and they are isolated from one another in both classA and classB?
Does again the static really change nothing in this case?
Methods don't have stacks, threads do. In your example threadMethod only uses local variables which are always private to the thread executing the method. It doesn't make any difference if the method is static or not as the method isn't sharing any data.
In this case there is no functional difference. Each thread gets it's own stack
Maybe you can be a little more clear. It doesn't matter if the function is declared static or not in most languages. Each thread has its own private statck.
Each thread would get it's own stack. There is no functional difference that I can tell between the two.
The only difference (obviously) is that the static version would be unable to access member functions/variables.

Resources